crud operations using rest api SharePoint Online

This SharePoint Rest API tutorial explains, how to do crud operations using rest api sharepoint online. Basically, we will see how to create, update, and delete SharePoint list items using Rest API in SharePoint Online or SharePoint 2013/2016/2019.

If you are new to Rest API SharePoint, then you can also check SharePoint Rest API Crud Operations.

Below script code, you can add to a script editor web part or to a content editor web part and it will work for both SharePoint Online as well as SharePoint On-premises.

You can also check, Create, Update and Delete List items using JavaScript Object Model (JSOM) in SharePoint Online/2013/2016.

crud operations using rest api SharePoint Online

Now, let us see how to crud operations using rest api sharepoint online.

Create SharePoint List Item using Rest API

Now, we will discuss how to insert the SharePoint list item using Rest API in SharePoint.

Here I have an announcements list and I am trying to insert the value to the Title column only.

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

<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Announcements')/Items";
var itemType = GetItemTypeForListName('Announcements');
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': itemType }, 'Title': 'Announcement - 1' }),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
alert(data+ ' List Item Created');
}

function onError (error) {
alert(JSON.stringify(error));
}

function GetItemTypeForListName(name) {return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";}
});
});
</script>
<input type="button" id="btnClick" value="Create List Item"/>

Once you click on the button in the web part page, you can see the item is added to the SharePoint list.

create update and delete list items using rest api

Insert SharePoint List Item using Rest API (Dynamically)

In the above code, we are inserting an item to the SharePoint list where we are passing a hardcoded value. But we can make it to dynamic also.

Here we will design an HTML form with some controls.

Here I have a SharePoint list name as “MyCompanyInfo” which has two columns known as Title and Industry. In this particular example let us take two text boxes, one for Title and one for Industry and one Submit button. On click on the Submit button, the item will be added in the SharePoint Online list.

All the HTML code and Rest API code we will put inside a script editor web part inside a SharePoint web part page.

<div id="AddListData">
<div>
Title:
<br />
<input type="text" id="txtTitle" />
</div>
<div>
Industry:
<br />
<input type="text" id="txtIndustry" />
</div>
<br />
<div>
<input id="btnSubmit" type="button" value="Submit" />
</div>
</div>
<div id="divResult"></div>

<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 () {
addListItem();
});
}

function addListItem() {
var title = $("#txtTitle").val();
var industry = $("#txtIndustry").val();
var fullUrl =_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Companies')/items";

$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Data.CompaniesListItem' },
'Title': title,
'Industry': industry
}),

headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded(sender, args) {
$("#divResult").html("Item successfully added!");
}

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

Once we save the page, the form will appear like below and the user can put title and industry and it will display successful message like below:

sharepoint rest api create list item
sharepoint rest api create list item

Now if you will look at the list, you can see the item added to the SharePoint list.

create update and delete list items using rest api sharepoint 2016
create list item sharepoint rest api

This is an example of create list item sharepoint rest api.

Update SharePoint List Item using Rest API

Now, we will see how to update a SharePoint list item using Rest API. You can use the below code to update the list item using Rest API in SharePoint.

You can also add the code into a script editor web part or content editor web part inside a web part page in SharePoint.

Here we are updating a list item having ID=2.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Announcements')/getItemById(2)";
var itemType = GetItemTypeForListName('Announcements');
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': itemType }, 'Title': 'Updated Announcement' }),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"IF-MATCH":"*"
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
alert('List Item Updated');
}

function onError(error) {
alert(JSON.stringify(error));
}

function GetItemTypeForListName(name) {return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";}
});
});
</script>

<input type="button" id="btnClick" value="Update List Item"/>

Now you can see, once you execute the code the SharePoint list item is updated.

sharepoint rest api update list item by id
sharepoint rest api update list item by id

This is an example of sharepoint rest api update list item.

Delete SharePoint List Item using Rest API

Finally, we will see how to delete an item from the SharePoint list using Rest API.

Here it will delete the SharePoint list item which has item id=2.

<input type="button" id="btnClick" value="Delete List Item"/>

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

<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Announcements')/getItemById(2)";
$.ajax({
url: requestUri,
type: "DELETE",
headers: {
"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('Item deleted');
}

function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>
create update and delete list items using rest api sharepoint online
sharepoint rest api delete list item

This is an example of sharepoint rest api delete list item.

SharePoint 2016 crud operations using Rest API

Let us first create a SharePoint list with custom template with the below name & columns. The SharePoint list has columns like:

  • LoanNumber
  • FirstName
  • LastName
  • LoanAmount

And the SharePoint list looks like below:

sharepoint add list item rest api
sharepoint add list item rest api

Key aspects to be known before we implement CRUD with REST in the client side object model in SharePoint.

How to Retrieve SharePoint Site URL Programmatically

In SharePoint _spPageContextInfo.webAbsoluteUrl retrieves current site URL. You can read a SharePoint 2013 article on: _spPageContextInfo javascript or jquery variable in SharePoint 2013

  • HTTP Methods in REST
  • Reading list data (GET)
  • Creating record/list item (POST)
  • Updating list item (MERGE/PATCH/PUT)
  • Delete list item (DELETE)
sharepoint online rest api crud operations
sharepoint online rest api crud operations

What is Request Digest in REST API?

A replay attack occurs when a valid request is sent to the server and a copy of that request is stored. The request is then sent multiple times (replayed). This can result in a variety of different issues the most common of which is duplication of data.

To prevent this, SharePoint requires the user to include a request-digest value with each creates, update and delete operation. This value is then used by SharePoint to identify non-genuine requests. Inside SharePoint Hosted apps, the request digest can be found by reading the value of the “__REQUESTDIGEST” object within the HTML page.

var digestValue = $("#__REQUESTDIGEST").val()

Note: this will only work on pages that contain the SharePoint Chrome element. The example above requires JQuery to work.

How to get List Item Types in Rest API

To update or create list items you will need to include the list item type. This is a string automatically created by SharePoint when the list is first created. Two possible ways to obtain this are:

  1. Perform a read operation on the list and locate the type within the returned set of elements. In JSON format the type can be found within the __metadata attribute of all of the returned list items. In Atom/XML format (the default format returned if your query from a web browser) you can find it in the category scheme attribute (labeled ‘term’) within the item.
  2. You can attempt to generate the value from the list name. In general list item types follow the convention SP.Data.ListNameListItem (e.g. list name is “Test”, list item type is SP.Data.TestListItem). However, this is not always the case. For example, SharePoint automatically capitalizes the first letter of the list name (e.g. list name “test” list item type is SP.Data.TestListItem). The following code snippet shows how to generate the List Item Type based on the list name.
Syntax:
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
}

Below are the various examples of SharePoint rest api crud operations.

SharePoint create list item rest api

With the below code block we can add the new list item in “LoanInformation” SharePoint List using Rest API.

sharepoint rest api insert list item
sharepoint rest api insert list item
// CREATE Operation Modules ———————- START ———————-
$("#btnAddLoans").click(function () {
var url = _spPageContextInfo.webAbsoluteUrl;
var title = $(‘#txtLnID’).val();
var lnFstName = $(‘#txtFstNm’).val();
var lnLstName = $(‘#txtLstNm’).val();
var lnAmnt = $(‘#txtLnAmnt’).val();
createListItemWithDetails("LoanInformation", url, title,lnFstName,lnLstName,lnAmnt, function ()
{
alert("Item has been created. Updating available items");
$(‘#txtLnID’).val("");
$(‘#txtFstNm’).val("");
$(‘#txtLstNm’).val("");
$(‘#txtLnAmnt’).val("");
ReadLoans();
Read();
}, function () {
alert("Ooops, an error occured. Please try again");
});
});

function createListItemWithDetails(listName, siteUrl, title, lnFstName,lnLstName,lnAmnt,success, failure) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": {"type": itemType },
"Title": title,
"FirstName":lnFstName,
"LastName":lnLstName,
"LoanAmont":lnAmnt
};

$.ajax({
url: siteUrl + "/_api/web/lists/getbytitle(‘" + listName + "‘)/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
// CREATE Operation Modules ———————- End ———————-

SharePoint update list item rest api

Below is the example of how to update list item using Rest API in SharePoint.

With the below code you can update the loan details of the selected loan number.

sharepoint update list item rest api
sharepoint update list item rest api
// Update Operation Releted Methods ———————- START ———————-
$( ".target" ).change(function() {
var selLnNumber = $(‘#chEditLnNumers’).find(":selected").val();
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle(‘LoanInformation’)/items?$filter=Title eq ‘" + selLnNumber+"‘";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
var objItems = data.d.results;
for (var i = 0; i < objItems.length; i++) {
$(‘#txtEdLnID’).val(objItems[i].Title);
$(‘#txtEdFstNm’).val(objItems[i].FirstName);
$(‘#txtEdLstNm’).val(objItems[i].LastName);
$(‘#txtEdLnAmnt’).val(objItems[i].LoanAmont);
}
}
function onError(error) {
alert(‘Error’);
}
});

$("#btnEditLoans").click(function(){
var selLnNumber = $(‘#chEditLnNumers’).find(":selected").val();
updateListItem(selLnNumber, "LoanInformation", _spPageContextInfo.webAbsoluteUrl, $(‘#txtEdLnID’).val(),$(‘#txtEdFstNm’).val(),$(‘#txtEdLstNm’).val(),$(‘#txtEdLnAmnt’).val(), function () {
alert("Item updated, refreshing avilable items");
$(‘#txtEdLnID’).val("");
$(‘#txtEdFstNm’).val("");
$(‘#txtEdLstNm’).val("");
$(‘#txtEdLnAmnt’).val("");
ReadLoans();
}, function () {
alert("Ooops, an error occured. Please try again");
});
});

function updateListItem(itemTitle, listName, siteUrl, title,lnFstName,lnLstName,lnAmnt, success, failure) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": title,
"FirstName":lnFstName,
"LastName":lnLstName,
"LoanAmont":lnAmnt
};

getListItemWithTitle(itemTitle, listName, siteUrl, function (data) {
$.ajax({
url: data.__metadata.uri,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": data.__metadata.etag
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}, function (data) {
failure(data);
});
}

// Update Operation Releted Methods ———————- END ———————-

SharePoint delete item rest api

Below is an example on how to delete list item using Rest API in SharePoint.

With the below code we can delete the selected loan number.

sharepoint delete list item rest api
sharepoint delete list item rest api
// Delete Operation Modules ———————- START ———————-

$("#btnDel").click(function () {
var selLnNumber = $(‘#chLnNumers’).find(":selected").val();
//alert(selLnNumber);
var itemId = $(‘#DeleteItems’).val();
deleteListItem(selLnNumber, "LoanInformation", _spPageContextInfo.webAbsoluteUrl, function () {
alert("Item deleted, refreshing avilable items");
ReadLoans();
}, function () {
alert("Ooops, an error occured. Please try again");
});

});

function deleteListItem(itemTitle, listName, siteUrl, success, failure) {
getListItemWithTitle(itemTitle, listName, siteUrl, function (data) {
$.ajax({
url: data.__metadata.uri,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-Http-Method": "DELETE",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"If-Match": data.__metadata.etag
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
},
function (data) {
failure(data);
});
}

// Delete Operation Modules ———————- End ———————-

Complete Output:

sharepoint rest api crud operations
sharepoint rest api crud operations

Here we saw, how to do insert, update, delete list operation using Rest API in SharePoint 2016/2019.

You may like SharePoint Rest API tutorials:

Once you run the code, you can see the SharePoint list item got deleted.

This Rest API SharePoint tutorial, we discuss below point.

  • Crud operations using rest api sharepoint online
  • How to create a list item using Rest API in SharePoint?
  • How to update the list item using Rest API in SharePoint Online/2013/2016.
  • And how to delete list items using Rest API in SharePoint Online or SharePoint 2013/2016.
  • >