SharePoint 2013 REST API CRUD Operations

Introduction 

SharePoint 2013 has greatly expanded the REST services available to developers. With this, we have much more SharePoint functionality exposed via JSOM and Web Services. The goal of this article is to provide how to perform basic create, read, update, and delete (CRUD) operations on lists and list items with the REST services.

SharePoint REST endpoint Overview:

The following table contains typical REST endpoint URL examples to get you started working with SharePoint data. Prepend http://server/site/_api/ to the URL fragments shown in the table to construct a fully qualified REST URL. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.
URL endpoint
Description
Supported HTTP Method
/_api/Web/Lists/ getbytitle('listname')
Getting a list details by its title and updating it as well. Ifanyone changes your list title, your code will break.
GET, POST
/_api/Web/Lists(guid'guid id of your list')
Same as above but changing list title will not affect the code.
GET, POST
/_api/Web/Lists/getbytitle(' listname ')/Fields
Retrieving all fields associated with a list and add new fields
GET, POST
/_api/Web/Lists/getbytitle('listname')/
Fields/getbytitle('fieldname')
Getting details of a field, modifying and deleting it.
GET, PUT, PATCH, MERGE, DELETE
/_api/Web/Lists/getbytitle('listname')
/Items
Retrieving all items in a list and adding new items
GET, POST
/_api/web/lists/getbytitle('listname')
/GetItemById(itemId)
 
This endpoint can be used to get, update and delete a single item.
GET, PUT, PATCH, MERGE, DELETE
/_api/lists/ getbytitle (‘'listname')/items?$orderby=Title
Order Your Results
GET, POST
/_api/lists/ getbytitle (‘'listname')/items?$select=Title,Id
Retrieve Selected Column Data value
GET, POST
/_api/web/lists/getbytitle('listname')/Items/
?$select=Title,FieldName/Id&$expand= FieldName /Id
Retrieving the lookup value
GET, POST


Ascending Order:
1.  /_api/web/lists/getbytitle('infolist')/items?$select=ID,Title,Employee,company&$orderby= Employee asc 
Descending Order:


1.  /_api/web/lists/getbytitle('infolist')/items?$select=ID,Title,Employee,company&$orderby= Employee desc  
  • Filtering items:
                      You can filter your list to contain only items which match a simple logical expression     using the $filterparameter.
  • Syntax: for this is $filter=(Column Internal Name operator value).
    See below examples,
    Filter by Title
    /_api/web/lists/getbytitle('infolist')/items?$filter=Employee eq ‘parth'
    Filter by ID:
    /_api/web/lists/getbytitle('infolist')/items?$filter=ID eq 2
    Filter by Date
    /_api/web/lists/getbytitle('infolist')/items?$filter=Start_x0020_Date le datetime'2016-03-26T09:59:32Z'
    Multiple Filters
    /_api/web/lists/getbytitle('infolist')/items?$filter=( Modified le datetime'2016-03-26T09:59:32Z') and (ID eq 2)
    Title name starts with the letter P
    /_api/web/lists/getbytitle(‘'infolist')/items?$filter=startswith(Title,‘P’)
    Return all items from the 'infolist'list modified in May
    /_api/web/lists/getbytitle(‘'infolist')/items? $filter=month(Modified) eq 5
  • OData query operators supported in the SharePoint REST service,

  • Paging items:

    The $top operators are used to implement paging for results. The $top operator specifies how many results to return.

    Syntax for this is $top Count. This returns top and records.

    See below example:
  • 1.  /_api/web/lists/getbytitle('infolist')/items?$top 5  

Note: The $skipoperator does not work in SharePoint 2013 on list items.it works only on Lists.

See below example

/_api/web/lists? Orderby Title desc&$skip

$expand:

This is very useful when dealing with person or lookup fields where only Id is returned. Using this we can get corresponding value based on Id.

See below example:

Lookup Field:Say there is City column in County list which is a lookup to Title column in Info List.
1.  /_api/web/lists/getbytitle('infolist')/items?$select=ID,Title,Employee,company,city/Id&$expand=city/Id  
People Field:

Let’s say a list has custom field: Author, it will return ‘AuthorId’ in response. What is the proper way to deal with people field? You need to use ‘$expand’ parameter to expand the field. 

Following REST URL gives your idea how to use $expand.
1.  /_api/web/lists/getbytitle('infolist')/items?$select=Author/Title&$expand=Author/Id 

Now, I will demo all the operations on list items, including retrieve, create, update and delete on list items.



Retrieve the list items

Here is the main code in detail:
1.  function retriveListItem()  
2.  {  
3.    
4.      $.ajax  
5.      ({  
6.          url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('companyInfo')/items?$select=Company,Industry",  
7.          type: “GET”,  
8.          data: data,  
9.          headers:  
10.         {  
11.             "Accept""application/json;odata=verbose",  
12.             "Content-Type""application/json;odata=verbose",  
13.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
14.             "IF-MATCH""*",  
15.             "X-HTTP-Method"null  
16.         },  
17.         cache: false,  
18.         success: function(data)   
19.         {  
20.             $("#ResultDiv").empty();  
21.             for (var i = 0; i < data.d.results.length; i++)   
22.             {  
23.                 var item = data.d.results[i];  
24.                 $("#ResultDiv").append(item.Company + "\t" + item.Industry + "<br/>");  
25.             }  
26.         },  
27.         error: function(data)  
28.         {  
29.             $("#ResultDiv").empty().text(data.responseJSON.error);  
30.         }  
31.     });  
32. }  
Create list item

Here is the main code in detail:
1.  function AddListItem()  
2.  {  
3.      var industryVal = $("#Industry").val();  
4.      var Company = $("#Company").val();  
5.      $.ajax  
6.          ({  
7.          url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('companyInfo')/items",  
8.          type: "POST",  
9.          data: JSON.stringify  
10.         ({  
11.             __metadata:  
12.             {  
13.                 type: "SP.Data.TestListItem"  
14.             },  
15.             Company: Company,  
16.             Industry: industryVal  
17.         }),  
18.         headers:  
19.         {  
20.             "Accept""application/json;odata=verbose",  
21.             "Content-Type""application/json;odata=verbose",  
22.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
23.             "X-HTTP-Method""POST"  
24.         },  
25.         success: function(data, status, xhr)  
26.         {  
27.             retriveListItem();  
28.         },  
29.         error: function(xhr, status, error)  
30.         {  
31.             $("#ResultDiv").empty().text(data.responseJSON.error);  
32.         }  
33.     });  
34. }  
Update list item


Here is the main code in detail:
1.  function updateListItem()  
2.  {  
3.      var industryVal = $("#Industry").val();  
4.      $.ajax  
5.      ({  
6.          url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('companyInfo')/items(7)"// list item ID  
7.          type: "POST",  
8.          data: JSON.stringify  
9.          ({  
10.             __metadata:  
11.             {  
12.                 type: "SP.Data.TestListItem"  
13.             },  
14.             Industry: industryVal  
15.         }),  
16.         headers:  
17.         {  
18.             "Accept""application/json;odata=verbose",  
19.             "Content-Type""application/json;odata=verbose",  
20.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
21.             "IF-MATCH""*",  
22.             "X-HTTP-Method""MERGE"  
23.         },  
24.         success: function(data, status, xhr)  
25.         {  
26.             retriveListItem();  
27.         },  
28.         error: function(xhr, status, error)  
29.         {  
30.             $("#ResultDiv").empty().text(data.responseJSON.error);  
31.         }  
32.     });  
Delete list item


Here is the main code in detail:
1.  function deleteListItem()  
2.  {  
3.      $.ajax  
4.      ({  
5.          url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('companyInfo')/items(7)",  
6.          type: "POST",  
7.          headers:  
8.          {  
9.              "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
10.             "IF-MATCH""*",  
11.             "X-HTTP-Method""DELETE"  
12.         },  
13.         success: function(data, status, xhr)  
14.         {  
15.             retriveListItem();  
16.         },  
17.         error: function(xhr, status, error)  
18.         {  
19.             $("#ResultDiv").empty().text(data.responseJSON.error);  
20.         }  
21.     });  
22. }  
Summary

In this article we explored SharePoint 2013 REST API for (CRUD) operations on list items level. I’ve tried to explore crud operation using REST Services, JavaScript Client Side Object Model, and SOAP Services to work on the client side.


The goal of this article is to provide how to perform basic create, read, update, and delete (CRUD) operations on lists and list items with the JSOM. I have explored the CRUD operation using Web Service.

Now, I will demo all the operations on list items, including retrieve, create, update and delete on list items.

 

Retrieve the list items


Here is the main code in detail:
1.  function retriveListItem()  
2.  {  
3.      //Get the current context   
4.      var context = new SP.ClientContext();  
5.      var list = context.get_web().get_lists().getByTitle(‘companyInfo’);  
6.      var caml = new SP.CamlQuery();  
7.      caml.set_viewXml("<View><Query><OrderBy><FieldRef Name=’Company’ Ascending='TRUE' /></OrderBy></Query></View>");  
8.      returnedItems = list.getItems(caml);  
9.      context.load(returnedItems);  
10.     context.executeQueryAsync(onSucceededCallback, onFailedCallback);  
11. }  
12.   
13. function onSucceededCallback(sender, args)  
14. {  
15.     var enumerator = returnedItems.getEnumerator();  
16.     //Formulate HTML from the list items   
17.     var MainResult = 'Items in the Divisions list: <br><br>';  
18.     //Loop through all the items   
19.     while (enumerator.moveNext())  
20.     {  
21.         var listItem = enumerator.get_current();  
22.         var companyName = listItem.get_item(“Company ");   
23.                 var Industry = listItem.get_item(“Industry ");   
24.                         MainResult += MainResult + companyName + "-" + Industry + "\n";  
25.                     }  
26.                     //Display the formulated HTML in the displayDiv element   
27.                 displayDiv.innerHTML = MainResult;  
28.             }  
29.             //This function fires when the query fails   
30.         function onFailedCallback(sender, args)  
31.         {  
32.             //Formulate HTML to display details of the error   
33.             var markup = '<p>The request failed: <br>';  
34.             markup += 'Message: ' + args.get_message() + '<br>';  
35.             //Display the details   
36.             displayDiv.innerHTML = markup;  
37.         } 
38.    }
39.
Create list item

Here is the main code in detail:

1.  function AddListItem()  
2.  {  
3.      var listTitle = "companyInfo";  
4.      //Get the current client context  
5.      context = SP.ClientContext.get_current();  
6.      var airportList = context.get_web().get_lists().getByTitle(listTitle);  
7.      //Create a new record  
8.      var listItemCreationInformation = new SP.ListItemCreationInformation();  
9.      var listItem = airportList.addItem(listItemCreationInformation);  
10.     //Set the values  
11.     Var industryVal = $("#Industry").val();  
12.     var Company = $("#Company").val();  
13.     listItem.set_item('Industry', +industryVal);  
14.     listItem.set_item('Company', +new item);  
15.     listItem.update();  
16.     context.load(listItem);  
17.     context.executeQueryAsync(AddListItemSucceeded, AddListItemFailed);  
18. }  
19.   
20. function AddListItemSucceeded()  
21. {  
22.     retriveListItem();  
23. }  
24.   
25. function AddListItemFailed(sender, args)  
26. {  
27.     alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
28. }  
Update list item


Here is the main code in detail:
1.  function updateListItem()  
2.  {  
3.      var ListName = "companyInfo";  
4.      var context = new SP.ClientContext.get_current(); // the current context is taken by default here  
5.      //you can also create a particular site context as follows  
6.      var lstObject = context.get_web().get_lists().getByTitle(ListName);  
7.      this.lstObjectItem = lstObject.getItemById(1);  
8.        
9.      Var industryVal = $("#Industry").val();  
10.     var Company = $("#Company").val();  
11.     lstObjectItem.set_item('Industry', “+industryVal + ”);  
12.     lstObjectItem.set_item('Company', ”+Company + ”);  
13.     lstObjectItem.update();  
14.         context.executeQueryAsync(Function.createDelegate(thisthis.onSuccess), Function.createDelegate(thisthis.onFailure));  
15. }  
16.   
17. function onSuccess()  
18. {  
19.     retriveListItem();  
20. }  
21.   
22. function onFailure(sender, args)  
23. {  
24.     alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
25. }  
Delete list item


Here is the main code in detail:
1.  function deleteListItem()  
2.  {  
3.      var listTitle = "companyInfo";  
4.      //get the current client context  
5.      context = SP.ClientContext.get_current();  
6.      var airportList = context.get_web().get_lists().getByTitle(listTitle);  
7.      //get the list item to delete  
8.      var listItem = airportList.getItemById(1);  
9.      //delete the list item  
10.     listItem.deleteObject();  
11.     context.executeQueryAsync(DeleteItemSucceeded, DeleteItemFailed);  
12. }  
13.   
14. function DeleteItemSucceeded()  
15. {  
16.     retriveListItem();  
17. }  
18.   
19. function DeleteItemFailed(sender, args)  
20. {  
21.     alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
22. }  
Summary

In this article we explored SharePoint JSOM for CRUD operations on list items level. Hope it will be helpful.


Example:


<script src="/SiteAssets/jquery-1.8.3.js">// Change source url
</script>
<script language="javascript" type="text/javascript"> 
$(document).ready(function() {


retriveListItem();
});
function retriveListItem()  
{  
  
    $.ajax  
    ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('ProductInfo')/items?$select=Title,Model",  
        type: "GET",  
        
        headers:  
        {  
            "Accept": "application/json;odata=verbose",  
            "Content-Type": "application/json;odata=verbose",  
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
            "IF-MATCH": "*",  
            "X-HTTP-Method": null  
        },  
        cache: false,  
        success: function(data)   
        { 
            //$("#ResultDiv").empty();  
            for (var i = 0; i < data.d.results.length; i++)   
            {  
                var item = data.d.results[i];  
               // $("#ResultDiv").append(item.Company + "\t" + item.Industry + "<br/>");  
               $("#ResultDiv").append("<tr align='middle'><td>"+item.Title+"</td><td>"+item.Model+"</td></tr>");  
              
            }  
        },  
        error: function(data)  
        {
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
function deleteListItem(){
$.ajax  
    ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('ProductInfo')/items(7)",  
        type: "POST",  
        headers:  
        {  
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
            "IF-MATCH": "*",  
            "X-HTTP-Method": "DELETE"  
        },  
        success: function(data, status, xhr)  
        {  
            retriveListItem();  
        },  
        error: function(xhr, status, error)  
        {  
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}
function  AddListItem(){

  var Company = $("#brand").val();  
    var industryVal = $("#model").val();  
    //alert(industryVal +"--"+Company );
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('ProductInfo')/items",  
        type: "POST",  
         headers:  
        {  
            "Accept": "application/json;odata=verbose",  
            "Content-Type": "application/json;odata=verbose",  
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
            "X-HTTP-Method": "POST"  
        },  
         data: JSON.stringify  
        ({  
            __metadata:  
            {  
                type: "SP.Data.ProductInfoListItem"  
            },  
            Title: Company,  
            Model: industryVal  
        }),
        success: function(data, status, xhr)  
        {  
            retriveListItem();  
        },  
        error: function(xhr, status, error)  
        {  
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}
function updateListItem(){
var Company = $("#brand").val(); 
  var industryVal = $("#model").val();  
    $.ajax  
    ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('ProductInfo')/items(1)", // list item ID  
        type: "POST",  
        data: JSON.stringify  
        ({  
            __metadata:  
            {  
                type: "SP.Data.ProductInfoListItem"  
            },  
            Title:Company,
            Model: industryVal  
        }),  
        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)  
        {  
            retriveListItem();  
        },  
        error: function(xhr, status, error)  
        {  
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}
</script>
<table>
<tr>
<td><button onclick="myFunction()">Retrive</button>
</td>
<td><button onclick="AddListItem()">Create</button>
</td>
</tr>
<tr>
<td><button onclick="updateListItem()">Update</button>
</td>
<td><button onclick="deleteListItem()">Delete</button>
</td>
</tr>
<tr>
Brand : <input type="text" name="Brand" id="brand"><br>
  Model:<input type="text" name="Model" id="model"><br>



</tr>
</table>
<table id="ResultDiv">
<tr><td>Brand</td><td>Model</td></tr>
</table>
<div ></div>

Comments

  1. This is a really informative knowledge, Thanks for posting this informative Information. Retrieve Company Details

    ReplyDelete

Post a Comment

Popular posts from this blog

Clearing the Configuration Cache for SharePoint

Add List Item Attachments to Task Form using Nintex Workflow and Forms