Forum Discussion
pcmarley
Feb 01, 2021Copper Contributor
Bad Request Creating Folder In SharePoint
Hello,
I'm trying to create a folder in SharePoint:
folder_url = 'https://<site url>/_api/web/folders'
headers = {
'Authorization': 'Bearer {}'.format(my_access_token),
'Accept': 'application/json; odata=verbose',
'Content-Type': 'application/json; odata=verbose',
}
req = {
'__metadata': {
'type': 'SP.Folder'
},
'ServerRelativeUrl': 'Shared Documents/mytestfolder'
}
r = requests.post(folder_url, data=req, headers=headers)
r.raise_for_status()
The return is always:
## 400 Client Error: Bad Request for URL: https://<site url>/_api/web/folders
Is there something I've missed?
Thanks.
- Rahul Mittal (ODSP)Microsoft
pcmarley
Can you try inserting a '/' in the front of your 'ServerRelativeUrl' parameter? i.e.'ServerRelativeUrl': '/Shared Documents/mytestfolder'
Provide ServerRelativeUrl in this format: "/sites/siteName/Shared Documents/mytestfolder".
Here are some of working examples you can refer to create a folder in SharePoint:
Creating folder with payload:
//HTML - function calling <button type="button" onclick="createFolderWithPayload()"> Add Folder with Payload</button> //JS - function to create a folder function createFolderWithPayload() { var folderEndpoint = _spPageContextInfo.webAbsoluteUrl + "/_api/web/folders"; var folderPayload = { "__metadata": { "type": "SP.Folder" }, "ServerRelativeUrl": "/sites/SPConnect/Shared Documents/folder1" }; $.ajax({ url: folderEndpoint, type: "POST", data: JSON.stringify(folderPayload), headers: { "X-RequestDigest": $("#__REQUESTDIGEST").val(), "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose" }, success: function (data) { console.log("Folder created successfully"); }, error: function (error) { console.log(error); } }); }
Creating folder without payload:
//HTML - function calling <button type="button" onclick="createFolder('/sites/SPConnect/Shared Documents', 'folder2')"> Add Folder </button> //JS - function to create a folder function createFolder(folderPath, newFolderName) { var folderEndpoint = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + folderPath + "')/folders/add(url=\'" + newFolderName + "\')"; $.ajax({ url: folderEndpoint, type: "POST", headers: { "X-RequestDigest": $("#__REQUESTDIGEST").val(), "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose" }, success: function (data) { console.log("Folder created successfully"); }, error: function (error) { console.log(error); } }); }
Please click Mark as Best Response if my post helped you to solve your issue. This will help others to find the correct solution easily. It also closes the item. If the post was useful in other ways, please consider giving it Like.