SharePoint Online Office 365 Create folder inside document library using Rest API
Introduction:
Here in this post, we will discuss how we can create a folder inside document library using REST API in SharePoint online Office 365. The same REST API code will also work as it is in SharePoint 2016 and SharePoint 2013.
In this example, we have taken a textbox and a submit button. The user can give a folder name in the textbox and click submit. On successful creation of the folder, it will show a successful message.
Here let us put code inside a script editor web part. So both the HTML and REST API code will be inside script editor web part inside a web part page.
HTML Code:
Below is the HTML code:
<div>
<strong>Enter Folder Name:</strong>
<input type="text" id="txtFolderName" />
<input type="button" id="btnSubmit" value="Submit" />
</div>
<div id="divResults"></div>
REST API code:
In the below code, we will create folder inside the "Documents" document library. In the metadata we are passing through ServerRelativeUrl where we want to create the document library.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createFolder();
});
}
function createFolder() {
var folderName = $("#txtFolderName").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/folders";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Folder' },
'ServerRelativeUrl': 'Shared Documents/' + folderName
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}
function onQuerySucceeded() {
$("#divResults").html("Folder created successfully !!!");
}
function onQueryFailed() {
alert('Error!');
}
</script>
Once you will Save the code, give a name for the folder and click on Submit. It will show a successful message like below:
Now if you will go to the Documents library, you can see the folder got created like below:
References:
You can see few posts on:
- Create folder inside document library using Rest API in SharePoint Online Office 365
- Create column in list using Rest API in SharePoint Online Office 365
- Create SharePoint Site using Rest API in SharePoint Online Office 365
Conclusion:
Here in this article, we have discussed how we can create folder inside document library using REST API in SharePoint online Office 365.