SharePoint API Create Folder | SharePoint REST API Create Folder

Do you want to learn how to create a document library and folder on the SharePoint site using REST API?

In this SharePoint tutorial, we will see how to create a document library and folder using SharePoint rest api. Also, we will see how we can get all folders and subfolders using SharePoint rest api.

Here are the topics we are going to cover:

  • SharePoint rest api create folder
  • SharePoint rest api create folder if not exists
  • SharePoint rest api gets all folders and subfolders
  • SharePoint api gets folders
  • SharePoint rest api document library
  • Sharepoint rest api create a folder with metadata
  • SharePoint rest api create a folder in a list
  • SharePoint rest api create a nested folder

SharePoint rest api document library

Here, we will see how to create a document library using SharePoint rest api.

For example, we will create a text box with a create button. In this setup, the text box will accept the Document Library name. Clicking on the create button will trigger a REST API request to create a Document Library in the SharePoint site.

Below, you can see the SharePoint rest api code that we have added to the Script editor webpart in the SharePoint classic site.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    function createDocumentLibrary() {
        var libraryName = $("#txtLibraryName").val();
        var siteUrl = _spPageContextInfo.webAbsoluteUrl;
        var fullUrl = siteUrl + "/_api/web/lists";
        $.ajax({
            url: fullUrl,
            type: "POST",
            data: JSON.stringify({
                '__metadata': { 'type': 'SP.List' },
                'AllowContentTypes': true,
                'BaseTemplate': 101,
                'ContentTypesEnabled': true,
                'Description': 'Your description here',
                'Title': libraryName
            }),
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: onQuerySucceeded,
            error: onQueryFailed
        });
    }

    function onQuerySucceeded(data) {
        var libraryId = data.d.Id;
        $("#divResults").html("Document library created successfully with ID: " + libraryId);
    }

    function onQueryFailed(error) {
        console.log("Error: " + JSON.stringify(error));
    }

    $(function () {
        $("#btnSubmit").on("click", function () {
            createDocumentLibrary();
        });
    });
</script>
<h2> Create Document Library </h2>
<label for="txtLibraryName">Library Name:</label>
<input type="text" id="txtLibraryName">
<button id="btnSubmit">Create Library</button>
<div id="divResults"></div>

Once you save the page, now fill out the form and click on the Create button to create the document library.

SharePoint rest api document library

Now you can see the Finance library get created in the SharePoint site using SharePoint rest api.

SharePoint rest api create document library

SharePoint API Create Folder

Here, we will see how to create a folder using SharePoint rest api.

For example, we will create a text box with a create button. Here, the text box will accept the folder name, and clicking on the create button will trigger the creation of a folder in the Finance Document Library on the SharePoint site using REST API requests.

Below, you can see the SharePoint rest api code that we have added to the Script editor webpart in the SharePoint classic site.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    function createFolder() {
        var folderName = $("#txtFolderName").val();
        var siteUrl = _spPageContextInfo.webAbsoluteUrl;
        var folderUrl = siteUrl + "/_api/web/getfolderbyserverrelativeurl('Finance')/folders/add('" + folderName + "')";

        $.ajax({
            url: folderUrl,
            type: "POST",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function () {
                alert("Folder created successfully!");
            },
            error: function (error) {
                alert("Error creating folder: " + JSON.stringify(error));
            }
        });
    }

    $(function () {
        $("#btnSubmit").on("click", function () {
            createFolder();
        });
    });
</script>

<label for="txtFolderName">Folder Name:</label>
<input type="text" id="txtFolderName">
<button id="btnSubmit">Create Folder</button>

Now you can provide the folder name and click the Create button to create the Folder in the Finance Document library in the SharePoint site 2013/2016.

sharepoint rest api create folder

Now you can see the Policies folder get created in the SharePoint library Finance in SharePoint site using SharePoint Rest Api.

sharepoint api create folder

SharePoint rest api create folder if not exists

Here, we will see how to create a folder if it does not exist in the SharePoint library using SharePoint rest api.

In this example, we will create a text box with a create button. The text box will accept the folder name, and clicking on the create button will trigger a check to determine whether the folder is available in the SharePoint Document Library (Finance) using the ‘Exists’ property.

See also  Create remote event receiver SharePoint Online Step by Step Tutorial

If the folder is available in the Document Library, the Exists property will return true. If it returns false, indicating that the folder is not available, we will proceed to create the folder in the Document Library. For this purpose, two functions have been created:

  1. checkFolder(): This function retrieves the folders from the specified path of the Document Library. If the folder already exists, it returns the message ‘Folder is already available.’ Otherwise, it calls the createFolder() function with the folder name.
  2. createFolder(): This function creates the folder with the specified name using the SharePoint REST API POST method.

Here is the code to create a folder if it does not exist using SharePoint rest api.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    function checkFolder() {
        var folderName = $("#txtFolderName").val();
        var siteUrl = _spPageContextInfo.webAbsoluteUrl;
        var folderPath = "Finance/" + folderName;
        var url = siteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderPath + "')/exists";

        $.ajax({
            url: url,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
            },
            success: function (data) {
                if (data.d.Exists) {
                    alert("Folder is already available");

                } else {
                    createFolder(folderName);
                }
            },
            error: function (error) {
                alert("Error checking folder existence: " + JSON.stringify(error));
            }
        });
    }

    function createFolder(folderName) {
        var siteUrl = _spPageContextInfo.webAbsoluteUrl;
        var folderUrl = siteUrl + "/_api/web/lists/getbytitle('Finance')/rootfolder/folders/add('"+ folderName +"')";

        $.ajax({
            url: folderUrl,
            type: "POST",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function () {
                alert("Folder created successfully!");
            },
            error: function (error) {
                alert("Error creating folder: " + JSON.stringify(error));
            }
        });
    }

    $(function () {
        $("#btnSubmit").on("click", function (event) {
            event.preventDefault();
            checkAndCreateFolder();
        });
    });
</script>

<label for="txtFolderName">Folder Name:</label>
<input type="text" id="txtFolderName">
<button id="btnSubmit">Create Folder</button>

Once you save the code in the script editor on the SharePoint site, after providing the folder name, click on the Create button; if it is not available, then it will create the folder.

SharePoint rest api create folder if not exists

Now, you can see the Folder was created in the Document library using SharePoint Rest API, as it is not available in the Library.

SharePoint Rest API to check if folder exist inside a folder in document library

If the folder exists it will notify you the folder is already available.

how to create a folder in sharepoint

SharePoint rest api gets folders

Here, we will see how to get a folder from the SharePoint site using SharePoint rest api.

For example, we have a Document library called Finance, which contains the below folders and internal Folders.

sharepoint api get folders

Here, we will create a SharePoint REST API request to retrieve all the folders from the specified document library and display them in the web part. The code defines two functions:

  1. getFolder(): This function retrieves all the folders from the Finance document library using the SharePoint REST API GET method.
  2. displayFolder(): This function checks if the length of the result returned by the SharePoint REST API is greater than 0. If true, it displays the folders in the web part. Otherwise, it notifies ‘No folders found’.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        getFolders();
    });

    function getFolders() {
        var siteUrl = _spPageContextInfo.webAbsoluteUrl;
        var folderUrl = siteUrl + "/_api/web/GetFolderByServerRelativeUrl('Finance')/Folders";

        $.ajax({
            url: folderUrl,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
            },
            success: function (data) {
                var folders = data.d.results;
                displayFolders(folders);
            },
            error: function (error) {
                console.log("Error loading folders: " + JSON.stringify(error));
            }
        });
    }

    function displayFolders(folders) {
        var folderList = $("#folderList");
        folderList.empty();

        if (folders.length > 0) {
            var listHtml = "<ul>";
            for (var i = 0; i < folders.length; i++) {
                listHtml += "<li>" + folders[i].Name + "</li>";
            }
            listHtml += "</ul>";

            folderList.html(listHtml);
        } else {
            folderList.html("No folders found.");
        }
    }
</script>
<h2> Folders in Finance Library </h2>
<div id="folderList"></div>

Now you can see all the folders are retrieved from the document library using SharePoint rest api.

sharepoint rest api get folders

SharePoint rest api gets all folders and subfolders

Here, we will see how to get all folders and subfolders using SharePoint rest api.

For example, in the Finance document library, we have four folders: Forms, Policies, External Documents, and Budgets. Within the Policies folder, there are three subfolders.

sharepoint rest api get all folders and subfolders

So, we will send a SharePoint REST API request to retrieve all the folders and subfolders from the SharePoint site.

For this, we will define 2 functions in the SharePoint REST API code:

  • getFolder(): In this function, we fetch all folders and subfolders from the document library. We construct a REST API URL to retrieve folders from the “Finance” document library or its subfolders based on the provided folder path.
  • Upon a successful response, we loop through the retrieved folders using a for loop. For each folder, we call getFolders() recursively to fetch its subfolders, passing the current folder’s path and name as arguments.
  • displayFolder(): This function is used to display all folders and subfolders available in the SharePoint library.
See also  How to check server health status check using PowerShell in SharePoint

Here is the full code to get all folders and subfolders using SharePoint rest api.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        loadFolders("", "");
    });

    function getFolders(folderPath, parentFolderName) {
        var siteUrl = _spPageContextInfo.webAbsoluteUrl;
        var folderUrl = siteUrl + "/_api/web/GetFolderByServerRelativeUrl('Finance" + folderPath + "')/Folders";

        $.ajax({
            url: folderUrl,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
            },
            success: function (data) {
                var folders = data.d.results;
                displayFolders(folders, parentFolderName);

                for (var i = 0; i < folders.length; i++) {
                    var subFolderPath = folderPath + "/" + folders[i].Name;
                    getFolders(subFolderPath, folders[i].Name);
                }
            },
            error: function (error) {
                console.log("Error loading folders: " + JSON.stringify(error));
            }
        });
    }

    function displayFolders(folders, parentFolderName) {
        var folderList = $("#folderList");
        var folderHeading = $("#folderHeading");

        if (folders.length > 0) {
            folderList.append("<h4>" + parentFolderName + "</h4>");
            var listHtml = "<ul>";
            for (var i = 0; i < folders.length; i++) {
                listHtml += "<li>" + folders[i].Name + "</li>";
            }
            listHtml += "</ul>";

            folderList.append(listHtml);
        }
    }
</script>
<h3 id="folderHeading">Finance</h3>
<div id="folderList"></div>

Once you save this code, you can see all folders and subfolders from the Finance Document library on the SharePoint site.

sharepoint rest api get folders and subfolders

SharePoint rest api create a folder with metadata

Here, we will see how to create a folder with metadata using SharePoint rest api.

For example, when a user creates a folder called “New Policy” in the Policies folder, they need to provide metadata such as Department and Release Date using SharePoint REST API.

SharePoint rest api create a folder with metadata

To achieve this, we will initiate an HTTP request to SharePoint to create a folder, retrieve the folder ID, and subsequently update its metadata.

To begin with, we’ll set up three columns: Folder name, Department, and Release Date, alongside a Create button. Upon clicking this button, the following functions will be invoked in the SharePoint REST API code:

  1. Create Folder(): This function creates the folder and passes its name to the getFolder() function.
  2. getFolder(): Here, we’ll obtain the folder ID based on the provided folder name data, such as data.ListItemAllFields.ID. Subsequently, it will call the UpdateFolder() function, passing along the ID, Department value, and Release Date.
  3. UpdateFolder(): Lastly, this function will create a folder along with its metadata using the SharePoint REST API’s POST method.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(function () {
        $("#createFolderBtn").click(function (event) {
            event.preventDefault(); // Prevent default form submission behavior
            
            var folderName = $("#folderName").val();
            var department = $("#department").val();
            var releaseDate = $("#releaseDate").val();
            CreateFolder(folderName, department, releaseDate);
        });
        
        function CreateFolder(folderName, department, releaseDate){
            console.log("Creating folder...");
            
            jQuery.ajax({
                "url" : _spPageContextInfo.siteAbsoluteUrl + "/_api/Web/Folders/add('/sites/Sales/Finance/Policies/" + folderName + "')",
                "type" : "POST",
                "headers" : { 
                        "accept" : "application/json; odata=verbose", 
                        "content-type" : "application/json; odata=verbose",
                        "X-RequestDigest" : $("#__REQUESTDIGEST").val()
                },
                success: function(data){
                    console.log("Folder created:", data);
                    GetFolder(folderName);
                },
                error: function(xhr, status, error){
                    console.log("Error creating folder:", error);
                }
            }); 

        }


        function GetFolder(folderName){
            console.log("Fetching folder...");
            var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('/sites/Sales/Finance/Policies/" + folderName + "')?$expand=ListItemAllFields";

            $.getJSON(url).then(function(data){
                 console.log("Folder fetched:", data);
                 UpdateFolder(data.ListItemAllFields.ID, $("#department").val(), $("#releaseDate").val());
            });
        }

        function UpdateFolder(id, department, releaseDate){  
            console.log("Updating folder...");
            $.ajax ({  
                url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Finance')/items("+ id +")", 
                type: "POST",  
                data: JSON.stringify({  
                    "__metadata":  
                    {  
                        type: "SP.Data.FinanceItem"  
                    },  
                    "Department": department, /=
                    "Release_x0020_Date": releaseDate, 
                   
                }),  
                headers:  
                {  
                    "Accept": "application/json;odata=verbose",  
                    "Content-Type": "application/json;odata=verbose",  
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
                    "IF-MATCH": "*",  
                    "X-HTTP-Method": "MERGE"  
                },  
                success: function(data, status, xhr)  
                {  
                    console.log("Metadata updated successfully.");
                },  
                error: function(xhr, status, error)  
                {  
                    console.log("Error updating metadata:", error);
                }  
            });
        }
    });
</script>

<!-- HTML UI -->
<label for="folderName">Folder Name:</label>
<input type="text" id="folderName">
<label for="department">Department:</label>
<select id="department">
    <option value="HR">HR</option>
    <option value="Finance">Finance</option>
    <option value="IT">IT</option>
</select>
<label for="releaseDate">Release Date:</label>
<input type="date" id="releaseDate">
<button id="createFolderBtn">Create Folder</button>

Now save the code in the Script editor webpart. Fill in the folder name, select the Department and Release date, and click on the Create button.

SharePoint rest api create a folder metadata

Now you can see the folder get created with metadata using SharePoint rest api.

create a folder with metadata using SharePoint rest api

SharePoint rest api create folder in a list

Here, we will see how to create a folder in List using SharePoint rest api.

See also  Registration form design in HTML and CSS with code

For example, we have the below Sales List, and we will create a ‘User manual’ folder using SharePoint rest api.

SharePoint rest api creates a folder in a list

To create a folder in the SharePoint list, need to enable the Folder option in List settings -Advance setting.

 rest api creates a folder in a SharePoint list


Then, we’ll set up two input fields along with buttons using HTML: one for the List name and another for the Folder name, alongside a Create button. When a user enters the List name and Folder name and clicks on the Create button, it will trigger the createFolderInList function. This function will then send a POST request to the SharePoint API, creating the specified folder in the designated list.

Add the below code to the Script editor webpart in SharePoint 2013/2016.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $("#btnCreateFolder").click(function() {
        var listTitle = $("#txtListTitle").val();
        var folderName = $("#txtFolderName").val();

        createFolderInList(listTitle, folderName);
    });

    function createFolderInList(listTitle, folderName) {
        var endpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";

        var folderMetadata = {
            "__metadata": { "type": "SP.Data." + listTitle + "ListItem" },
            "Title": folderName,
            "ContentTypeId": "0x0120" // Content Type ID for folders
        };

        $.ajax({
            url: endpointUrl,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(folderMetadata),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function (data) {
                console.log("Folder created successfully:", data);
                alert("Folder created successfully!");
            },
            error: function (error) {
                console.error("Failed to create folder:", error);
                alert("Failed to create folder. Please check the console for details.");
            }
        });
    }
});
</script>

 <h3>Create Folder in SharePoint List</h3>
    <label for="txtListTitle">List Title:</label>
    <input type="text" id="txtListTitle" placeholder="Enter list title"><br><br>
    
    <label for="txtFolderName">Folder Name:</label>
    <input type="text" id="txtFolderName" placeholder="Enter folder name"><br><br>

    <button id="btnCreateFolder">Create Folder</button>

Now fill out the form and click on the Create button to create the folder in the list using SharePoint rest api.

how to create folder in sharepoint

Now you can see the user manual folder get created in the SharePoint list using SharePoint rest api.

how to create folder in sharepoint rest api

SharePoint rest api create nested folder

Here, we will see how to create a nested folder using SharePoint rest api.

For example, within the Invoice Folder, we will create a subfolder for each Department. Inside each Department folder, we will further organize folders based on user names, all done using the SharePoint REST API.

Sharepoint rest api create nested folder


or this purpose, we’ve designed two input fields along with buttons using HTML: Department and User name, alongside the Create button.

When a user fills in the Department and User name fields and clicks on the Create button, it activates the createNestedFolder function. This function, in turn, initiates a POST request to the SharePoint API, facilitating the creation of a nested folder within the specified Folder.



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        // Function to create nested folders
        function createNestedFolders() {
            var siteUrl = "https://szg52.sharepoint.com/sites/Sales";
            var department = $("#department").val();
            var userName = $("#userName").val();
            var folderUrl = siteUrl + "/_api/web/getfolderbyserverrelativeurl('/sites/Sales/Finance/Invoice')/folders";
            var folderData = {
                "__metadata": { "type": "SP.Folder" },
                "ServerRelativeUrl": "/sites/Sales/Finance/Invoice/" + department + "/" + userName
            };

            // Create department folder
            $.ajax({
                url: folderUrl,
                type: "POST",
                data: JSON.stringify(folderData),
                headers: {
                    "accept": "application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: function(data) {
                    console.log(department + " folder created successfully:", data);
                },
                error: function(error) {
                    console.error("Failed to create " + department + " folder:", error);
                }
            });
        }

        // Button click event handler
        $("#createFoldersBtn").on("click", function(event) {
            // Prevent the default form submission behavior
            event.preventDefault();
            // Call the function to create nested folders
            createNestedFolders();
        });
    });
</script>

<h2>Create User in Invoice Folder</h2>
<label for="department">Select Department:</label>
<select id="department">
    <option value="HR">HR</option>
    <option value="Finance">Finance</option>
    <option value="IT">IT</option>
</select>
<br> <br>
<label for="userName">User Name:</label>
<input type="text" id="userName">
<br><br>
<button id="createFoldersBtn">Create Folders</button>

Now, add the Department and User name. Click on the create button to send a SharePoint rest api request to create a nested folder.

rest api create nested folder in SharePoint

Now you can see inside the invoice folder we have created a Finance folder; inside that, we have created a User 2 folder using SharePoint rest api.

rest api create nested folder SharePoint

Also, you may like:

Conclusion

In this SharePoint tutorial, we saw how to create a SharePoint rest api document library, SharePoint rest api create a folder. Also, we discussed SharePoint rest api create folder if not exists, SharePoint api gets folders, and Sharepoint rest api create a nested folder with various examples.

  • Hi, Can you guide me on how to do this from a native application like a website with only html pages/aspx pages ( application is outside of sharepoint context ) to create a list item/ folder in a library in a sharepoint online site.

  • >