SharePoint Rest API [Complete Tutorial With Examples]

If you want to become a SharePoint Online developer, then you should learn SharePoint Rest API. In this SharePoint tutorial, I will explain how to work rest API in SharePoint Online, various SharePoint rest api examples, and SharePoint rest api crud operations.

SharePoint Rest API

The SharePoint REST API is a service provided by SharePoint that allows for interaction with SharePoint data remotely using RESTful principles. It exposes all the SharePoint entities and operations that are available in the other SharePoint client APIs, enabling developers to perform CRUD (Create, Read, Update, Delete) operations and execute queries against SharePoint lists, libraries, and other data constructs. This makes it a flexible and powerful choice for integrating with SharePoint from any technology that supports HTTP and REST.

SharePoint Rest API is another form of client object model similar to JSOM, or CSOM.

SharePoint Rest API HTTP commands

Now let us try to understand SharePoint rest api HTTP commands. If you want to work with Rest API in SharePoint, the first thing we need to do is construct a Restful HTTP request by using the OData protocol standard.

If you want to do create, read, update, and delete operations using SharePoint Rest API, then we need to use the GET, POST, PUT, MERGE, DELETE, and PATCH HTTP methods.

GET

In rest API, we use the HTTP GET method if we want to read information from the SharePoint server or if we want to retrieve information from a SharePoint list if we want to read items from the SharePoint list. So mostly for the Read operations, we use the GET method.

POST

In SharePoint, if you want to create or update operations like creating a list or an item in a SharePoint Online list, you use the Rest API POST operations. In Rest API POST operations, if any properties are not required, they are set to their default values.

PUT/MERGE

In SharePoint Online, if you want to update an existing object, like an update item in a SharePoint list or update the SharePoint list title, then we can use the Rest API PUT and MERGE operations.

There is a little difference between HTTP PUT and MERGE in SharePoint rest api.

In the REST API MERGE HTTP method, setting properties is optional, and if any properties that you don’t explicitly set, keep their current property.

For the PUT operations, it is mandatory to set up all the required properties while updating SharePoint objects. For the optional properties, if you do not specify the values, they will be set to the default properties.

DELETE

As the name suggests, the HTTP DELETE method is used when we want to delete any SharePoint objects such as deleting SharePoint list, list items, documents, etc.

Now, I hope you got an idea of which HTTP commands, we should use while working with SharePoint rest api CRUD operations.

For doing any kind of operation in SharePoint using Rest API, the first thing we need to do is to create the rest endpoint. All the rest endpoint URL starts with:

https://SiteURL/Sites/SiteName/_api/

Example:

Below is an example of SharePoint Online.

https://tsinfotechnologies.sharepoint.com/sites/SPGuides/_api/

For on-premises versions, the Rest api endpoint will be like the below:

http://bsahoo3:8787/sites/Training/_api/

Here are various SharePoint rest api endpoint examples; I have taken a SharePoint Online site as a reference, but the Rest API endpoints will be the same for SharePoint on-premises.

But while working with Rest API code, we can get the site URL by using the below JavaScript variable:

_spPageContextInfo.webAbsoluteUrl
OperationSharePoint Rest API endpoint
Get SharePoint site collectionhttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/site
Get specific SharePoint site or webhttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/web
Get SharePoint site titlehttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/web/title
Get all lists from a SharePoint sitehttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/web/lists
Get all items from a SharePoint listhttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/web/lists/getbytitle(‘Trainings’)/items
Get SharePoint list title using Rest APIhttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/web/lists/getbytitle(‘Trainings’)?select=Title
Get all columns from a SharePoint listhttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/web/lists/getbytitle(‘Trainings’)/Fields
Get SharePoint list by using a list GUIDshttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/Web/Lists(List GUIDs)
Get SharePoint list item by item idhttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/web/lists/GetByTitle(‘Trainings’)/GetItemById(2)
Get SharePoint logged in user information or current user informationhttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/Web/currentUser
Get selected fields for SharePoint list itemshttps://tsinfotechnologies.sharepoint.com/sites/SPGuides/_api/web/lists/getbytitle(‘Trainings’)/Items?select=ID,Title,FirstName,LastName
Get all SharePoint site usershttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/Web/siteusers
Get all SharePoint groups from the sitehttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/Web/sitegroups
Get all users from a SharePoint grouphttps://<tenant-name>.sharepoint.com/sites/SPGuides/_api/Web/sitegroups(Id)/users
Rest API endpoint examples

You can put the rest endpoint in any of the browsers, and you can see the result.

https://<tenant-name>.sharepoint.com/sites/Finance/_api/web/lists/getByTitle('Employees')/items/getbyid(7)

Once you enter the URL, if you have not signed in, then it will give you the error message like Access denied. If you have already logged in, then you can see the output below in XML.

how to use sharepoint rest api in a browser

If you are trying to open the same SharePoint rest api endpoint in Internet Explorer, you can see the output will come like this below:

how to use sharepoint online rest api in a browser

SharePoint Rest API crud operations

Now, let us see examples of SharePoint rest api crud operations. I will show you here how to create, update, delete, and display items from a SharePoint Online list using Rest API.

For the rest api code, we can add a script editor web part in a SharePoint Online web part page.

I have also created a video on CRUD operations; you can have a look at it below:

Get List Items using SharePoint Rest API

The code below explains how to get list items using SharePoint rest api.

Here, I have added a button, and on button click, we can retrieve SharePoint list items using rest api and display them. It will display all the SharePoint list items in a dialog box in the onSuccess method.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<button onclick="GetListItems();" type="button">Get All List Items​</button>

<script>
function GetListItems()
{
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employees')/items";
$.ajax({
url: url,
type: "GET",
headers:
 {
"accept":"application/json; odata=verbose"
},
success: onSuccess,error: onError
});
}

function onSuccess(data) {
var items = data.d.results;
var allItems='';
for (var i = 0; i < items.length; i++) {
allItems+="Item ID- "+ items[i].Id+ " : Title- " + items[i].Title + '\r\n';
}
alert(allItems);
}

function onError(error) {alert(JSON.stringify(error));
}
</script>

Save the above code in a script editor web part and then click on the button; you can see the output below:

SharePoint rest api get all list items

This is how to get all list items in SharePoint Online using rest api.

Insert an item to SharePoint using Rest API

Here is how to insert an item to a SharePoint list using Rest API.

I added a button control. Once the user clicks on the button, the item will be inserted into the list using the Rest API code.

  • POST: Here, it is going to be a HTTP POST request because it is an insert operation. For any kind of insert or update operation, we have use the HTTP POST request.
  • __REQUESTDIGEST: While doing any rest api POST operation, we need to send a valid request digest to the SharePoint page. This is a token, and it helps SharePoint to understand that the request is a valid request.

SharePoint always includes a request digest token on every page in a hidden field as __REQUESTDIGEST. So, while working with Rest API, we need to get this hidden value from the field and send it with the request in a parameter as X-RequestDigest. The token is valid for 30 minutes. It will be like the following:

"X-RequestDigest": $("#__REQUESTDIGEST").val()

It is a must for any SharePoint rest api POST request.

Another important is the type which we do like below:

type: "SP.Data.EmployeesListItem"

Ideally, you should follow the below method to get it.

'SP.Data.' + 'List Internal Name' + 'ListItem'

Example: SP.Data.' + 'Employees' + 'ListItem' = SP.Data.EmployeesListItem

Below is the complete code to insert the item to SharePoint using rest api.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<button onclick="InsertItem();" type="button">Insert Item to SharePoint List​</button>

<script>
function InsertItem()
{
var restendpoint = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employees')/items";
$.ajax
({
url: restendpoint,
type: "POST",
data: JSON.stringify
(
{
__metadata:
{
type: "SP.Data.EmployeesListItem"
},
Title : "Bijay Kumar"
}),
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "POST"
},
success: function()
{
alert("Item added to the SharePoint list");
},
error: function()
{
alert("Error Occurred!");
}
});
}
</script>

Once you run the code and click on the button, you can see the item will be inserted to the SharePoint list.

insert item to SharePoint using rest api

Update an item in the SharePoint list using Rest API

Now, let us see another example on SharePoint rest api update list item. Updating an item is almost similar to inserting an item into the SharePoint list; the only difference is the rest of the endpoint.

We need to get the item by id, and then we can update.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<button onclick="UpdateItem();" type="button">Update Item (ID=4)​</button>

<script>
function UpdateItem()
{
var restendpoint = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employees')/items/getbyid(4)";

$.ajax({  
    url: restendpoint,  
    type: "POST",  
    headers: {  
        "accept": "application/json;odata=verbose",  
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
        "content-Type": "application/json;odata=verbose",  
        "IF-MATCH": "*",  
        "X-HTTP-Method": "MERGE"  
    },  
    data: "{__metadata:{'type':'SP.Data.EmployeesListItem'},Title:'Bhawana Rathore'}",
    success: function(data) {  
        alert('Item updated successfully!');
    },  
    error: function(error) {  
        alert(JSON.stringify(error));  
    }  
});  

}
</script>

Once you save the code and click on the button, it updates the list item whose id=5.

sharepoint rest api update list item

Here is another example on SharePoint rest api update list item by id.

Delete list item using SharePoint Rest API

Here is how to delete the list item using SharePoint rest api.

This will also be a POST operation, but we have to pass an additional parameter as “X-Http-Method”: “DELETE”.

The rest of the endpoint is the same as updating the list item because we will first get the item by ID, which item you want to delete.

Below is the complete code to delete SharePoint list items using Rest API.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<button onclick="DeleteItem();" type="button">Delete Item (ID=3)​</button>

<script>
function DeleteItem()
{
var restendpoint = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employees')/items/getbyid(3)";

$.ajax({  
    url: restendpoint,  
    type: "POST",    
    headers: {  
        "Accept": "application/json;odata=verbose",  
        "X-Http-Method": "DELETE",  
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
        "If-Match": "*"  
    },  
    success: function(data) {  
        alert('SharePoint list item deleted');  
    },  
    error: function(data) {  
        alert('Error Occurred!');  
    }
});  

}
</script>
sharepoint rest api delete list item

So, this is an example of deleting a list item in SharePoint using Rest API.

SharePoint rest api __metadata

__metadata is very important while working with SharePoint rest api, especially while doing any HTTP POST operations like insert and update.

Through __metadata we provide various information required to create or update operations. Another important property we set is the type parameter.

For example, if you want to create a list in the SharePoint Online site by using Rest API, then we need to pass type=SP.List and other information like the list Title, Description, BaseTemplate, etc. It looks like below:

data:  JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true,
 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'This is the list description', 'Title': 'This is List Title' })

Similarly, if you want to create a site in SharePoint using Rest API, we have to pass the type= SP.WebInfoCreationInformation, and we also need to pass other data required to create a site like Title, Description, Url, WebTemplate, Language, etc. It should look like below:

data: JSON.stringify(
        {'parameters': {
            '__metadata':  {'type': 'SP.WebInfoCreationInformation' },
            'Url': 'SiteURL',
            'Title': 'Site Title',
            'Description': 'Site Description,
            'Language':1033,
            'WebTemplate':'sts',
            'UseUniquePermissions':false}
        }
    )

This is why we use SharePoint rest api __metadata.

SharePoint Rest API Examples

Now, let us check out a few SharePoint rest API examples.

Example-1: Create a List using SharePoint Rest API

In the first rest API example, I will show you how to create a list using SharePoint Rest API.

Here, to create a SharePoint list using Rest API, we will give a user an option to give a title and description for the SharePoint list. When a user clicks on the Submit button, it will create a list in SharePoint.

<h2>Create SharePoint List using Rest API in SharePoint</h2>
<br/>
<table>
<tr>
<td>Enter List Title:</td>
<td><input type="text" id="txtTitle" size="40"/></td>
</tr>
<tr>
<td>Enter List Description:</td>
<td><textarea rows="4" cols="50" id="txtDescription"></textarea></td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" id="btnClick" value="Create List using Rest API"/>
</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var title = $("#txtTitle").val();
var description = $("#txtDescription").val();
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true,'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': description, 'Title': title }),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('List Created Successfully !');
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>

Once you run the code, you can see a form like the one below. In it, the user can provide the list title and description and click on the Create List using the Rest API button. The code will then display a successful message.

Create SharePoint list using rest api

Once you open the Site Contents page, you can see the SharePoint list was created successfully like below:

create list using rest api in sharepoint online

This is how to create a list in SharePoint Online using Rest API.

I have also recorded a video on this; have a look at it.

Example-2: Delete a SharePoint list using Rest API

Now, I will show you how to delete a SharePoint list using Rest API. We will provide the user an option to enter the list name and a button to delete a list from the SharePoint site using Rest API.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<h2>Delete SharePoint List using Rest API in SharePoint Online</h2>
<br/>
<table>
<tr>
<td>Enter List Title:</td>
<td><input type="text" id="txtTitle" size="40"/></td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" id="btnClick" value="Delete List using Rest API"/>
</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var title = $("#txtTitle").val();
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle(" + "'" + title + "'"+")";
alert(requestUri);
$.ajax({
url: requestUri,
type: "DELETE",
headers: {
"accept":"application/json",
"X-RequestDigest":$("#__REQUESTDIGEST").val(),
"IF-MATCH":"*"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('List Deleted');
}
function onError
(error) {
alert(error);
}
});
});
</script>

Example-3: Update SharePoint List using Rest API SharePoint

Now we will see how to update the SharePoint list using the rest api in SharePoint.

Here, I will update the list title & description using the rest api. In the form, I am giving a user to provide the old list title, new list title, and new list description and a button.

<h2>Update SharePoint List using Rest API in SharePoint</h2>
<br/>
<table>
<tr>
<td>Enter Old List Title:</td>
<td><input type="text" id="txtOldTitle" size="40"/></td>
</tr>
<tr>
<tr>
<td>Enter New List Title:</td>
<td><input type="text" id="txtNewTitle" size="40"/></td>
</tr>
<tr>
<td>Enter New List Description:</td>
<td><textarea rows="4" cols="50" id="txtNewDescription"></textarea></td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" id="btnClick" value="Update List using Rest API"/>
</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var oldtitle = $("#txtOldTitle").val();
var newtitle = $("#txtNewTitle").val();
var newdescription = $("#txtNewDescription").val();
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle(" + "'" + oldtitle + "'"+")";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': 'SP.List' }, 'Description': newdescription, 'Title': newtitle }),
headers: {
"X-HTTP-Method":"MERGE",
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('List Title and Description Updated Successfully !');
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>

Once you save the code, the user can enter the old list title, new list title & new list description and click on the Update List using the Rest API button.

update list title using rest api sharepoint 2013/2016

In the Site Contents page, you can see the list details has been updated like below:

Update SharePoint list using Rest API

This is how to update a list in SharePoint using Rest API. I have shown how to update the list title and description using Rest API in SharePoint Online as well as SharePoint On-premises.

Example-4: Filter SharePoint list items by the current user using Rest API

Here, I have a SharePoint online Announcement list with a Title column, and various users have inserted some data. The list looks like below:

rest api filter

Now, let us see how to filter SharePoint list items by the current user using Rest API.

By using the _spPageContextInfo.userEmail, we are retrieving the current logged-in user email ID.

In the rest endpoint URL, we are filtering based on the current user email ID, which we are comparing with the Created By’s email ID field. The internal name of the Created By column in “Author”.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<h1>Training Announcements</h1><br/>
<div id="result"></div>
<script>
var LoginName=_spPageContextInfo.userEmail;
var newURL="/_api/Web/Lists/GetByTitle('TrainingAnnouncements')/Items?$select=Title,ID,Author/EMail&$filter=Author/EMail eq '"+ LoginName +"'&$expand=Author/Id";
jQuery().ready(function () {
function getItems(url) {
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
getItems( newURL).done(function(data){
var fullresult="";
data.d.results.forEach(function(item){ // no need for oldskool for loops
fullresult+=item.Title +'<br><br>';
});
jQuery('#result').html(fullresult);
});
});
</script>

Once you add the code, you can see the rest api filter records based on the current user.

rest api filter example sharepoint

Example-5: Get list items created by the current user using SharePoint REST API

Here is how to get SharePoint list items created by the current user with Rest API.

In this SharePoint Rest API example, I have a SharePoint Online custom list as the Department is there. We will retrieve items created by the logged-in user from the department list.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<h1>Departments Added by Logged In User</h1><br/>
<div id="result"></div>
<script>
var userId = _spPageContextInfo.userId;
var newURL="/_api/Web/Lists/GetByTitle('Departments')/Items?$filter=AuthorId eq " + userId;
jQuery().ready(function () {
function getItems(url) {
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
getItems( newURL).done(function(data){
var fullresult="";
data.d.results.forEach(function(item){ // no need for oldskool for loops
fullresult+=item.Title +'<br><br>';
});
jQuery('#result').html(fullresult);
});
});
</script>

I have added the code inside a script editor web part, and you can see the results below:

Get list items created by logged in user with REST api in SharePoint Online

Example-6: Get current user details using SharePoint Rest API

You can use current user details, such as ID, user name, email ID, etc., using SharePoint Rest API.

The Rest endpoint to retrieve current logged-in user details:

https://<tenant-name>.sharepoint.com/sites/Finance/_api/web/currentuser

Similarly, if we want to retrieve specific properties like Email, LoginName, Title, UserID, etc, then we need to modify the endpoint URL to like below:

https://<tenant-name>/sites/Finance/_api/web/currentuser?$select=Email,LoginName,Title,Id

By using the above rest endpoint we can retrieve only selected properties.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<input type="button" id="btnClick" value="Get User Details using Rest API"/>
<script>
$(function(){
$("#btnClick").click(function(){
GetUserDetails();
});
});
function GetUserDetails() {
var url = "https://<tenant-name>.sharepoint.com/sites/Finance/_api/web/currentuser";
$.ajax({
url: url,
headers: {
Accept: "application/json;odata=verbose"
},
async: false,
success: function (data) {
alert("User Name: "+data.d.Title +" Email ID: " +data.d.Email+" User ID: " +data.d.Id);
},
eror: function (data) {
alert("An error occurred. Please try again.");
}
});
}
</script>

Once you run the above code, you can see the current user details below:

Get current user details using Rest API in SharePoint Online

Here is another approach: we can get logged-in user details using Rest API in SharePoint Online.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<h1>Logged In User Details</h1><br/>
<div id="result"></div>
<script>
var newURL="/_api/web/currentuser";
jQuery().ready(function () {
function getLoggedInUserDetails(url) {
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
getLoggedInUserDetails(newURL).done(function(data){
var fullresult="";
fullresult+="User Name: "+data.d.Title +"<br><br>";
fullresult+="Email ID: "+data.d.Email +"<br><br>";
fullresult+="ID: "+data.d.Id +"<br><br>";
jQuery('#result').html(fullresult);
});
});
</script>

Once you run the above code, you can see the logged-in user details below in SharePoint.

Get Logged in user details using Rest API in SharePoint

Example-7: Create a Folder using SharePoint Rest API

We can also easily create a folder in the document library using SharePoint Rest API.

Below is the Rest API code to create a folder in the SharePoint Online document library.

<strong>Folder Name:</strong>
<input type="text" id="txtName" />
<input type="button" id="btnCreate" value="Create Folder" />
<br/>
<div id="divmessage"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnCreate").on("click", function () {
createFolder();
});
}

function createFolder() {
var folderName = $("#txtName").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/folders";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Folder' },
'ServerRelativeUrl': 'Best Practices Documents/' + folderName
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onSuccess,
error: onFail
});
}

function onSuccess() {
$("#divmessage").html("SharePoint Folder Created Successfully !!!");
}

function onFail() {
alert('Error!');
}
</script>

Once you Save the web part page, the form will appear like below:

create folder in document library using rest api

Put the folder name and click on the button “Create Folder”, the folder will be created in the document library.

SharePoint create folder rest api

This is how to create a folder in the SharePoint Online document library using Rest API.

Example-8: Display SharePoint list data using HTML and jQuery table using Rest API

I will show you how to display SharePoint list data in an HTML table using Rest API.

According to our requirement, we have a SharePoint Online list as TrainingRequests with few columns and data like the below:

List Columns:

  • Title
  • Course
  • Comments
  • TrainerName
  • TrainingType
display sharepoint list data in html table using javascript

Now, according to our business requirement, we need to display this list data in an HTML table inside a web part page.

Example-1 (Without People Picker Column):

Below is the example where we are displaying all the columns in a grid except people picker control.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnGetTrainingRequests").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('TrainingRequests')/items";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
var items = data.d.results;
var fullResults = '<table id="tableCars" style="width:100%" border="1 px"><thead><tr><td><b>Title</b></td>' + '<td><b>Course</b></td>'+ '<td><b>TrainingType</b></td>' +'<td><b>Comments</b></td>' + '</tr></thead><tbody>';
for (var i = 0; i < items.length; i++) {
fullResults += '<tr>';
fullResults += '<td>' + items[i].Title + '</td>';
fullResults += '<td>' + items[i].Course + '</td>';
fullResults += '<td>' + items[i].TrainingType + '</td>';
fullResults += '<td>' + items[i].Comments + '</td>';
fullResults += '</tr>';
}
$('#resultsTable').append(fullResults);
}
function onError(error) {
alert('Error');
}
});
});
</script>
<input type="button" id="btnGetTrainingRequests" value="Get All Training Requests"/>
<br/><br/>
<table id='tableCars' style="width: 100%;" border="1 px">
<tr>
<td>
<div id="resultsTable" style="width: 100%"></div>
</td>
</tr>
</table>

Once you save the page and click on the button, you can see the output will come like below:

bind SharePoint Online list data using HTML table

Example-2: (With People picker column)

Here, we will see how to retrieve people picker column values using Rest API and display them in the HTML table or grid. We have “TrainerName” is a people picker column.

To retrieve the value from a people picker column, we need to change the rest endpoint like below:

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('TrainingRequests')/items?$select=Title,Course,TrainingType,Comments,TrainerName/EMail,TrainerName/FirstName,TrainerName/LastName&$expand=TrainerName";

Then we can access the Trainer FirstName like below “TrainerName.FirstName”.

The full code will look like below:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnGetTrainingRequests").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('TrainingRequests')/items?$select=Title,Course,TrainingType,Comments,TrainerName/EMail,TrainerName/FirstName,TrainerName/LastName&$expand=TrainerName";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
var items = data.d.results;
var fullResults = '<table id="tableCars" style="width:100%" border="1 px"><thead><tr><td><b>Title</b></td>' + '<td><b>Course</b></td>' + '<td><b>TrainerName</b></td>' + '<td><b>TrainingType</b></td>' +'<td><b>Comments</b></td>' + '</tr></thead><tbody>';
for (var i = 0; i < items.length; i++) {
fullResults += '<tr>';
fullResults += '<td>' + items[i].Title + '</td>';
fullResults += '<td>' + items[i].Course + '</td>';
fullResults += '<td>' + items[i].TrainerName.FirstName + '</td>';
fullResults += '<td>' + items[i].TrainingType + '</td>';
fullResults += '<td>' + items[i].Comments + '</td>';
fullResults += '</tr>';
}
$('#resultsTable').append(fullResults);
}
function onError(error) {
alert('Error');
}
});
});
</script>
<input type="button" id="btnGetTrainingRequests" value="Get All Training Requests"/>
<br/><br/>
<table id='tableCars' style="width: 100%;" border="1 px">
<tr>
<td>
<div id="resultsTable" style="width: 100%"></div>
</td>
</tr>
</table>

Once you run the code, you can see the output; in the Trainer Name, we can see the FirstName from the People picker control.

display sharepoint list data in html table using jquery

Example-9: Display SharePoint list data in jQuery data table using Rest API

Now, we will discuss how to display SharePoint list data in a jQuery data table using Rest API and jQuery.

The code you can use to bind list data to the jQuery table in SharePoint.

DataTables is a powerful Javascript library (js) for adding interactive features to HTML tables. This datatables provides inbuilt paging, sorting, search, etc. There are very interactive and beautiful features provided by the js library.

To work with DataTables, you need two files.

  • DataTables Javascript file (Can add the from DataTables CDN https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js)
  • DataTables CSS file (Can add the from DataTables CDN https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css)

If you want to use more extensions, you can get the js files from the below URL: https://cdn.datatables.net/

The full path is given form like below:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>

Apart from this, you can also download both the files and stores inside a document library, style library, or site assets library in SharePoint site like below:

<link rel="stylesheet" type="text/css" href="/DataTables/datatables.css">
<script type="text/javascript" charset="utf8" src="/DataTables/datatables.js"></script>

Here I have a SharePoint Online list which has some data like below:

Display SharePoint list data in jquery datatables using Rest API

Now, we will see how to display the list data using grid and datatables using Rest API in SharePoint.

<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://<tenant-name>.sharepoint.com/sites/DevSite/SiteAssets/RetriveListItemsRestAPI.js"></script>
<!--External js file to get data from SharePoint List -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/css/dataTables.jqueryui.min.css">
</head>
<body>
<div>
<table id="Employee" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>EmpName</th>
<th>Gender</th>
<th>ContactNumber</th>
<th>Department</th>
<th>Address</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
RetriveListItemRestAPI.js:-
$(document).ready(function() {
GetItems();
});
function GetItems() {
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var oDataUrl = siteUrl + "/_api/web/lists/getbytitle('MyCompanyEmployeeList')/items?$select=Title,Gender,ContactNumber,Department,Address";
$.ajax({
url: oDataUrl,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: OnSuccess,
error: OnFailure
});
}
function OnSuccess(data) {
try {
$('#Employee').DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"mData": "Title"
},
{
"mData": "Gender"
},
{
"mData": "ContactNumber"
},
{
"mData": "Department"
},
{
"mData": "Address"
}
]
});
} catch (e) {
alert(e.message);
}
}
function OnFailure(data, errMessage) {
alert("Error: " + errMessage);
}

Once you run the code, you can see it displays the data using datatables and Rest API in SharePoint.

Display SharePoint Online list data in jquery datatables Rest API

I hope this SharePoint tutorial explains how to bind SharePoint Online list data using an HTML table or jQuery Datatable using Rest API and jQuery in SharePoint.

Conclusion

I hope you know now how to use SharePoint rest API with these examples.

You may also like:

  • >