Search code examples
javasharepointmicrosoft-graph-apimicrosoft-graph-sdks

Error when try to add metadata to file in Sharepoint with MSGraph v6 for Java


I have a file in sharepoint (I know the DriveItemId) and I would like to add metadata (let's say, title) to it. I'm using MS Graph SDK for Java (6.3.0) for that purpose. I try to do it like this:

GraphServiceClient client = .... ;
Map<String, Object> metadata=... ;
...    
final DriveItem driveItem = client.drives().byDriveId(<parent_folder_id>).items().byDriveItemId(driveItemId).get();
driveItem.setAdditionalData(metadata);
client.drives().byDriveId(<parent_folder_id>).items().byDriveItemId(driveItemId).patch(driveItem);

But I've got error when execute "patch":

com.microsoft.graph.models.odataerrors.ODataError: Invalid request
    at com.microsoft.graph.models.odataerrors.ODataError.createFromDiscriminatorValue(ODataError.java:36)
    at com.microsoft.kiota.serialization.JsonParseNode.getObjectValue(JsonParseNode.java:210)
    at com.microsoft.kiota.http.OkHttpRequestAdapter.lambda$throwIfFailedResponse$0(OkHttpRequestAdapter.java:672)

Are there any other ways to achieve that?


Solution

  • I think you need to update fields on a listItem associated with a driveItem

    // get the listItem associated with the driveItem
    final ListItem listItem = graphClient.drives().byDriveId("").items().byDriveItemId("").listItem().get(e -> e.queryParameters.select = new String[] { "sharepointids" });
    
    // prepare fieldValueSet to be updated
    FieldValueSet fieldValueSet = new FieldValueSet();
    HashMap<String, Object> additionalData = new HashMap<String, Object>();
    additionalData.put("Title", "New value");
    fieldValueSet.setAdditionalData(additionalData);
    
    // read sharepoint ids
    SharepointIds sharepointIds = listItem.getSharepointIds();
        
    // update fields of the listItem associated with the driveItem
    graphClient.sites().bySiteId(sharepointIds.getSiteId()).lists().byListId(sharepointIds.getListId()).items().byListItemId(sharepointIds.getListItemId()).fields().patch(fieldValueSet);