Cord
Cord

Reputation: 317

How to create a new root folder in SharePoint Online Document Library with Graph API in Python

I am able to create folders in folders below the document library root and upload files everywhere, but i can't quite figure out the POST path to create a new folder in the Drive (Document Library) root. Everything I find assumes already some default folder. The POST examples provided in MS documentation requires a parent item ID. I have tried many permutations of the POST syntax.

None of these seem to work:

This is what I use to create folders below the doc lib root:

folder_path = 'https://graph.microsoft.com/v1.0/drives/{drive_id}/items/{parent_item_id}/children'
folder_path_values = folder_path.format(drive_id=driveid, parent_item_id=parentid)

Here's the code I use to submit the request that is not working:

# Some code to get the access_token and the API permissions we have are Files.ReadWrite.All and Sites.ReadWrite.All

driveid = 'b!qyL8-Uu96Uud....JR4eRG9FpH-Z5'
name = 'Drafts'
headers = {'Authorization': 'Bearer ' + access_token}

folder_path = 'https://graph.microsoft.com/v1.0/drives/{drive_id}'
folder_path_values = folder_path.format(drive_id=driveid)

new_folder = {
   "name": name,
   "folder": {},
   "@microsoft.graph.conflictBehavior": "replace"
}

res = requests.post(folder_path_values, json=new_folder, headers=headers)

That gives me a 400 error - i cannot seem to figure out the right syntax for creating a new folder (drive) in the root of a document library.

Upvotes: 1

Views: 1190

Answers (1)

user2250152
user2250152

Reputation: 20823

If you want to create a folder under the root, then you can use PATCH

PATCH /drives/id/root:/drafts
{
    "folder": {},
    "@microsoft.graph.conflictBehavior": "fail"
}

Code

driveid = 'b!qyL8-Uu96Uud....JR4eRG9FpH-Z5'
name = 'Drafts'
headers = {'Authorization': 'Bearer ' + access_token}

folder_path = 'https://graph.microsoft.com/v1.0/drives/{drive_id}/root:/'+name
folder_path_values = folder_path.format(drive_id=driveid)

new_folder = {
   "folder": {},
   "@microsoft.graph.conflictBehavior": "replace"
}

res = requests.patch(folder_path_values, json=new_folder, headers=headers)

If you want to have another folder on the same level as you root, then it's not possible because drive can have only one top-most folder.

Upvotes: 0

Related Questions