Search code examples
c#microsoft-graph-apionedrivemicrosoft-graph-sdks

Getting the drive's items from Microsoft Graph API: The request is malformed or incorrect


I am trying to get a drive's items via the Microsoft Graph Api (SDK) and tried the following options:

  1. _graphServiceClient.Drives[driveInfo.Id].Items.Request().GetAsync():, this unfortunately results in an error with message error with message "The request is malformed or incorrect" and code "invalidRequest". If I execute _graphServiceClient.Drives[driveInfo.Id].Request().GetAsync() however, I get back all drives but the Items property is null.

  2. _graphServiceClient.Drives[driveInfo.Id].Request().Expand(d => d.Items).GetAsync(), this also results in an error with message "The request is malformed or incorrect" and code "invalidRequest".

I don't know how to go on from here, still researching, but the documentation is leaving me clueless at the moment. Anyone success with either .Expand() or getting the actual files from a Drive?

Thanks, Y


Solution

  • You only use Items when you're fetching a single DriveItem:

    await graphClient
      .Me
      .Drive
      .Items[item.Id] 
      .Request()
      .GetAsync();
    
    await graphClient
      .Drives[drive.Id]
      .Items[item.Id]
      .Request()
      .GetAsync();
    

    When you want to retrieve a DriveItem collection, you need to specify the root folder:

    await graphClient
      .Me
      .Drive
      .Root // <-- this is the root of the drive itself
      .Children // <-- this is the DriveItem collection
      .Request()
      .GetAsync();
    
    await graphClient
      .Drives[drive.Id]
      .Root 
      .Children
      .Request()
      .GetAsync();
    

    The SDK unit tests are a good source for quick examples. For example, OneDriveTests.cs contains several examples for addressing Drives and DriveItems.