Search code examples
sharepointmicrosoft-graph-apionedrivemicrosoft-graph-files

Sharepoint : create a new file in a specific drive with graph API


In order to create a new file in a drive (a simple text file with some content), I try to call an API with MS Graph.

PUT /sites/{site-id}/drive/items/{parent-id}:/{filename}:/content

The drive where I want to put the file is name "myFolder" and has this driveId :

b!e5bDF5eRbU2Y7P3gHeS-0F1abPhpWXdOvSUViyWpqX876IbeJvIPS5-tf--QTQiz

This drive is in the root site.

Here :

  • {site-id} : "root"
  • {parent-id} : is the id of the drive which will be the parent
  • {filename} : text.txt

If I had to create this file in a subsite it would

  • {site-id}:/sites/{subsite-id}/drive/items/{parent-id}:/{filename}:/content

So theoretically my URL should be the following :

https://graph.microsoft.com/v1.0/sites/root/drives/b!e5bDF5eRbU2Y7P3gHeS-0F1abPhpWXdOvSUViyWpqX876IbeJvIPS5-tf--QTQiz:/text.txt:/content

Here :

  • {site-id} : "root"
  • {parent-id} : is the id of the drive which will be the parent
  • {filename} : text.txt

I also define the request header Content-Type as text/plain My issue is that I retrieve an error message :

{
  "error": {
    "code": "BadRequest",
    "message": "Resource not found for the segment 'content'.",
    "innerError": {
      "date": "2020-06-26T14:19:11",
      "request-id": "812b7ee0-3ecb-4d41-a8c5-59419b086f51"
    }
  }
}

Solution

  • This is expected error since for addressing a file within a drive (which is document library in SharePoint) a folder container needs to be provided:

    So, instead of query

    https://graph.microsoft.com/v1.0/sites/root/drives/{drive-id}:/{file-name}:/content
    

    it should be

    https://graph.microsoft.com/v1.0/sites/root/drives/{drive-id}/root:/{folder-path}/{file-name}:/content
    

    where folder-path corresponds to Test folder in your case

    References

    Addressing resources in a drive on OneDrive