SharePoint 2016 crud operations using Rest API and jQuery on list or document library

This article we will deep dive on SharePoint 2016 List / Library CRUD operation with client-side technologies like Rest API and jQuery. After completing this SharePoint 2016 tutorials you will get to know how we can do crud operations like create, read, update and delete operations in a list or document library using Rest API and jQuery.

Learn SharePoint crud operations using Rest API with examples.

sharepoint rest api crud operations
sharepoint rest api crud operations

SharePoint 2016 crud operations using Rest API and jQuery

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";
}

SharePoint rest api crud operations

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

You may like following SharePoint Rest API tutorials:

Hope this SharePoint example helps to know SharePoint rest API crud operations. We saw how to do insert, update, delete list operation using Rest API in SharePoint.

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

Krishna Vandanapu

I am Krishna.Vandanapu a SharePoint architect working in IT from last 13+ years, I worked in SharePoint 2007, 2010, 2013, 2016 and Office 365. I have extensive hands on experience in customizing SharePoint sites from end to end. Expertise in SharePoint migration tools like Sharegate, Doc Ave and Metalogix. Migrated SharePoint sites from SharePoint 2007 to 2010 and 2010 to 2013 several times seamlessly. Implementing CSOM with Microsoft best practices. Spent quality time in configuring SharePoint application services like User Profile, Search, Managed Meta data services etc. Now exploring SharePoint Framework and SharePoint 2019

  • […] SharePoint 2016 crud operations using Rest API and jQuery on list or document library […]

  • […] SharePoint 2016 crud operations using Rest API and jQuery on list or document library […]

  • […] SharePoint 2016 crud operations using Rest API and jQuery on SharePoint list or document library […]

  • >