Explore the Experience in SharePoint 2013

Tuesday, March 3, 2015

How to Insert, Update Delete List items using REST API in SharePoint2013 ?

12 comments
Hello,

In this post we are going learn how to do CRUD(Create, Read, Update and Delete) operations using SharePoint2013 REST API .


Before learning how to write the script, you should know where to write the script?

This depends on your requirement, lets suppose if you are implementing a visual web part then you can write the script on your user control( .ascx file) in script tag as shown below. You can write your script in a function and then call that function wherever you want.

In the below script I am calling the script on document ready function

<script type="text\javascript">

$(document).ready( function(){

             // Calling function 
             GetListItembyID();

});

function GetListItembyID(){

            //write your script to get the list item based on id here

}

</script>

Or else you can write the script in a Content Editor web part like as mentioned above.


Reading list item based on item id

Here is the following scenario, I just want to fetch some data based on item id from a list.

In this case we need to use GET http method to fetch/read items. Following are the sample snippets which I used to fetch some of the columns(Title, Name, Email ) information of the item having ID as 1 from the list titled EMPMaster.


$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/getitembyid('1')/?$select=Title, Name, Email",
              type: "GET",
              headers: {
                               "accept":  "application/json; odata=verbose"
                            },
              success: function(data){
                                alert(data.d.Title); //You will get title here
                                alert(data.d.Name); //You will get name here
                                alert(data.d.Email); //You will get email here
                            },
              error: function(err){
                                alert("Error while fetching list item: " + JSON.stringify(err));
                            }

          });


Reading multiple list items

In the below snippet I used to fetch columns(Title, Name, Email ) information of all items from the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items?$select=Title, Name, Email",
              type: "GET",
              headers: {
                               "accept":  "application/json; odata=verbose"
                            },
              success: function(data){
                               // Looping multiple items
                               $.each(data.d.results, function(index, item){
                                     alert(Item: " + index);
                                     alert(item.Title); //You will get title here
                                     alert(item.Name); //You will get name here
                                     alert(item.Email); //You will get email here
                                 });
                            },
              error: function(err){
                                alert("Error while fetching list items: " + JSON.stringify(err));
                            }

          });



Inserting list item

In the below snippet I have added list item having columns(Title, Name, Email ) values as "ABC", "XYZ", xyz@abc.com in to the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items",
              type: "POST",
              data: JSON.stringify({
                                                   '__metadata': {'type': 'SP.Data.EMPMasterListItem' },
                                                   'Title': 'ABC',
                                                   'Name': 'XYZ',
                                                   'Email': 'xyz@abc.com'
                                                }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val()
                            },
              success: function(data){
                              alert("Item added successfully!");
                            },
              error: function(err){
                                alert("Error while adding item: " + JSON.stringify(err));
                            }

          });



Updating list item based on item id

In the below snippet I have updated list item column "Name" value to "XYZ1" having id as 1  in the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items(1)",
              type: "POST",
              data: JSON.stringify({
                                                   '__metadata': {'type': 'SP.Data.EMPMasterListItem' },
                                                   'Name': 'XYZ1'
                                                }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "MERGE",
                               "If-Match": "*"
                            },
              success: function(data){
                              alert("Item updated successfully!");
                            },
              error: function(err){
                                alert("Error while updating item: " + JSON.stringify(err));
                            }

          });



Deleting list item based on item id

In the below snippet I have deleted list item having id as 1 in the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items(1)",
              type: "POST",
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "DELETE",
                               "If-Match": "*"
                            },
              success: function(data){
                              alert("Item deleted successfully!");
                            },
              error: function(err){
                                alert("Error while deleting item: " + JSON.stringify(err));
                            }

          });


So thats it for now. Hope you learn some basic operations using REST apis in SharePoint 2013.

Happy coding. Cheers!!! :)


12 comments :

  1. Nice Post,

    I need to add multiple items to the list in a single call / bulk update, add,delete

    Thanks in advance.

    ReplyDelete
  2. Can't we updated multiple items to the list in single call?

    ReplyDelete
  3. 100% working code to perform CRUD operation...Thanks
    Keep Updating

    ReplyDelete
  4. the blog is good and Interactive it is about Mulesoft API Developer it is useful for students and Mulesoft Developers for more updates on Mulesoft mulesoft Online training

    ReplyDelete
  5. This Blog Provides Very Useful and Important Information. I just Want to share this blog with my friends and family members. Learn Mulesoft Online

    ReplyDelete
    Replies
    1. I too want to share with my friends

      Delete
  6. It is very interesting to read this information. Thank you for sharing this... SharePoint Development 2013

    ReplyDelete