16

Can anyone explain or point me to a link with samples of doing Update, Delete using Jquery with the SharePoint 2010 Rest API?

I have the insert working and of course queries since the MSDN documentation explains and every tutorial on the net explains queries but just wondering if anyone ever inserts, updates, deletes data instead of only samples and tutorials on querying? Yes I know I can use the CSOM but I want to learn how this is done via jquery and sharepoint rest?

Also I want to use Merge for updating.

Here's the working insert code:

function insertMilestone() {
            var mileStonesListUrl = "/_vti_bin/listdata.svc/Milestones";    
               var milestone = {};
               milestone.Title = "Testing from REST";

               var entry = JSON.stringify(milestone);

               $.ajax({
                   type: "POST",
                   url: mileStonesListUrl,
                   data: entry,
                   contentType: "application/json; charset=utf-8",
                   error: function (xhr) {
                       alert(xhr.status + ": " + xhr.statusText);
                   },

                   success: function () {
                       getAll();

                   }
               });
           }
Fab
  • 904
  • 2
  • 14
  • 38

3 Answers3

21

How to perform CRUD operations using SharePoint 2010 REST Interface

Create

In order to perform a Create operation via REST, you must perform the following actions:

  • Create an HTTP request using the POST verb.
  • Use the service URL of the list to which you want to add an entity as the target for the POST.
  • Set the content type to application/json.
  • Serialize the JSON objects that represent your new list items as a string, and add this value to the request body

JavaScript example:

function createListItem(webUrl,listName, itemProperties, success, failure) {

    $.ajax({
        url: webUrl + "/_vti_bin/listdata.svc/" + listName,
        type: "POST",
        processData: false,
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(itemProperties),
        headers: {
            "Accept": "application/json;odata=verbose"
        },
        success: function (data) {
            success(data.d);
        },
        error: function (data) {
            failure(data.responseJSON.error);
        }
    });
}

Usage

var taskProperties = {
    'TaskName': 'Order Approval',
    'AssignedToId': 12
};

createListItem('https://contoso.sharepoint.com/project/','Tasks',taskProperties,function(task){
    console.log('Task' + task.TaskName + ' has been created'); 
  },
  function(error){
    console.log(JSON.stringify(error));
  }
);

Read

In order to perform a Read operation via REST, you must perform the following actions:

  • Create an HTTP request using the GET verb.
  • Use the service URL of the list item to which you want to add an entity as the target for the GET.
  • Set the content type to application/json.

JavaScript example:

function getListItemById(webUrl,listName, itemId, success, failure) {
    var url = webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")";
    $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            success(data.d);
        },
        error: function (data) {
            failure(data.responseJSON.error);
        }
    });
}

Usage

getListItemById('https://contoso.sharepoint.com/project/','Tasks',2,function(taskItem){
    console.log(taskItem.TaskName); 
  },
  function(error){
    console.log(JSON.stringify(error));
  }
);

Update

To update an existing entity, you must perform the following actions:

  • Create an HTTP request using the POST verb.
  • Add an X-HTTP-Method header with a value of MERGE.
  • Use the service URL of the list item you want to update as the target for the POST
  • Add an If-Match header with a value of the entity’s original ETag.

JavaScript example:

function updateListItem(webUrl,listName,itemId,itemProperties,success, failure)
{
   getListItemById(webUrl,listName,itemId,function(item){

      $.ajax({
         type: 'POST',
         url: item.__metadata.uri,
         contentType: 'application/json',
         processData: false,
         headers: {
                "Accept": "application/json;odata=verbose",
                "X-HTTP-Method": "MERGE",
                "If-Match": item.__metadata.etag
         },
         data: Sys.Serialization.JavaScriptSerializer.serialize(itemProperties),
         success: function (data) {
                success(data);
         },
         error: function (data) {
                failure(data);
         }
      });

   },
   function(error){
       failure(error);
   });

}

Usage

var taskProperties = {
    'TaskName': 'Approval',
    'AssignedToId': 12  
};


updateListItem('https://contoso.sharepoint.com/project/','Tasks',2,taskProperties,function(item){
    console.log('Task has been updated'); 
  },
  function(error){
    console.log(JSON.stringify(error));
  }
);

Delete

To delete an entity, you must perform the following actions:

  • Create an HTTP request using the POST verb.
  • Add an X-HTTP-Method header with a value of DELETE.
  • Use the service URL of the list item you want to update as the target for the POST
  • Add an If-Match header with a value of the entity’s original ETag.

JavaScript example:

function deleteListItem(webUrl, listName, itemId, success, failure) {
    getListItemById(webUrl,listName,itemId,function(item){
        $.ajax({
            url: item.__metadata.uri,
            type: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-Http-Method": "DELETE",
                "If-Match": item.__metadata.etag
            },
            success: function (data) {
                success();
            },
            error: function (data) {
                failure(data.responseJSON.error);
            }
        });
    },
   function (error) {
       failure(error);
   });
}

Usage

deleteListItem('https://contoso.sharepoint.com/project/','Tasks',3,function(){
    console.log('Task has been deleted'); 
  },
  function(error){
    console.log(JSON.stringify(error));
  }
);

Please follow List Items manipulation via REST API in SharePoint 2010 article for a more details.

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • I want to add the attachment, How can I add multiple attachments with SharePoint 2010 REST Interface? – Ram Sep 21 '17 at 14:19
9

Here is the update and delete, it wasn't as hard as I thought it was going to be and it works. Hopefully this will help someone out because there is so much bogus information on using the REST API and I see a zillion posts on querying but none on Insert, Update, Delete.

//update
           function updateMilestone(id) {

               var mileStonesUrl = "/_vti_bin/listdata.svc/Milestones";
               mileStonesUrl = mileStonesUrl + "(" + id+ ")";


               var beforeSendFunction;

               var milestoneModifications = {};
               milestoneModifications.Title = "Updated from REST";

               var updatedMilestoneData = JSON.stringify(milestoneModifications);


               //update exsiting milestone
               beforeSendFunction = function (xhr) {
                   xhr.setRequestHeader("If-Match", "*");
                   // Using MERGE so that the entire entity doesn't need to be sent over the wire.
                   xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
               }

               $.ajax({
                   type: "POST",
                   contentType: "application/json; charset=utf-8",
                   processData: false,
                   beforeSend: beforeSendFunction,
                   url: mileStonesUrl,
                   data: updatedMilestoneData,
                   dataType: "json",
                   error: function (xhr) {
                       alert(xhr.status + ": " + xhr.statusText);
                   },

                   success: function () {
                       alert("Updated");
                       getAll();

                   }
               });




     function deleteMilestone(id) {

               var mileStonesUrl = "/_vti_bin/listdata.svc/Milestones";
               mileStonesUrl = mileStonesUrl + "(" + id+ ")";

               $.ajax({
                   type: "DELETE",
                   contentType: "application/json; charset=utf-8",
                   processData: false,                       
                   url: mileStonesUrl,                     
                   error: function (xhr) {
                       alert(xhr.status + ": " + xhr.statusText);
                   },
                   success: function () {
                       alert("deleted");
                       getAll();

                   }
               });

           }




           }
Fab
  • 904
  • 2
  • 14
  • 38
  • Have you tried this:http://spservices.codeplex.com/ it is awesome if you want to use javascript to talk to Sharepoint – Luis Jul 24 '13 at 03:12
  • 1
    Yes, I've seen the spservices but it's uses the CSOM and xml and all that jazz, CSOM is not that difficult, U2U CAML builder for the queries makes it easy. It's cool but using the REST API with jquery is really awesome. I'm really trying to learn the inner workings instead of abstracting all the learning with using someone elses library, I would rather code my own framework, I don't have time constraints and it's nice understanding all of it. I didn't understand REST merge but now I do. I have jquery datatables with custom UI and pretty much a single page application inside sharepoint. – Fab Jul 24 '13 at 23:46
  • 2
    I'm surprised when I google all the examples are all for Gets and the rest are for SPServices. Doesn't anyone use the REST API ? Why are there no posts on CRUD, even the SP Pluralsight Course the author stops on geting data. – Fab Jul 24 '13 at 23:52
  • 1
    I am doing Single Apps as well inside SharePoint. The first thing I did was hookup Service Stack to it and do my own implementation using Server Object Model. It works pretty, Add knockout, Sammy and Require to that and it's win all over the place – Luis Jul 25 '13 at 01:11
  • Nice, I've been learning Service Stack and actually was planning on doing the same thing since we have a lot of external databases. I'll have to checkout Sammy, haven't used that before. – Fab Jul 26 '13 at 03:31
  • Cool , let me know if you need a hand at some stage. inputflip {at} gmail {dot} com – Luis Jul 26 '13 at 06:29
  • 1
    Hi Vadim Gremyachev.Do you have some solution for upload attachment file to custom list use rest api and javascript? – Kem Bardly Apr 14 '17 at 18:20
  • I do, also I've switced to using the SharePoint PNP.js framework which makes using the rest api easy. https://github.com/SharePoint/PnP-JS-Core/wiki/Working-With:-Files – Fab Apr 19 '17 at 17:21
-1

I recently worked with the REST API for SP 2013, as a Example POC that can be used for any call implementation i.e. JQuery, C# etc.

Using POSTMAN

First get your digest token:

A method was found on this site : http://tech.bool.se/basic-rest-request-sharepoint-using-postman/[Credit where credit is due]

POST

http://<SharePoint Domain Url>/sites/<Site name>/_api/contextinfo

Header:

Accept : application/json;odata=verbose

Body: Clear the body ​

From the payload use "FormDigestValue" value and put it into your headers with the key : X-RequestDigest when making actions that alter items in SharePoint.

Reading data:

GET

http://<SharePoint Domain Url>/sites/<Site name>/_api/web/getfolderbyserverrelativeurl('/Sites/<Site Name>/Shared Documents/My Folder')/files?$select=Name

Headers:

Accept : application/json;odata=verbose​

When it comes to create, update , delete you need the digest token or an authorization token to perform these actions, this token is highlighted at the begining to to retrieve.

​Creating Data POST

http://<SharePoint Domain Url>/sites/<Site Name>/_api/web/folders​

Headers:

Accept : application/json;odata=verbose

X-RequestDigest : 'GUID looking toking'

Content-Type : application/json;odata=verbose

Body:

{ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/Sites/<Site Name>/Shared Documents/Some Folder/POC3'}​

Note: 'ServerRelativeUrl' the folder on the end POC3 is the folder that I want to create

Related resources: http://msdn.microsoft.com/en-us/library/office/fp142380(v=office.15).aspx

Note: PostMan was used for this example and other application may need you to url encode the endpoint.

The above Request Structure can be used for all requests, the related resource highlights some of the standard methods that can be used with the REST Api

leeroya
  • 485
  • 7
  • 12
  • 1
    This is for 2013, not 2010. 2010 uses `/_vti_bin/ListData.svc`, not `/_api/web/folders​`. And you'd want `/_api/web/lists`, anyway, in 2013. Giving pieces instead of a working example, and handing off reference links isn't how we want to answer questions. – vapcguy Mar 14 '19 at 16:18
  • 1
    Thank you @vapcguy for the feedback, this was answered in 2014, This was one of my first answers and would have created a repository if I knew better back then – leeroya Mar 15 '19 at 20:56
  • Yeah, I guess I should've figured that, since it was 5 yrs ago. I just wanted to make sure others knew the differences in the APIs and call attention to it in case you (and others that might see it) were still answering similarly. Glad you've grown as the time passed. Peace. – vapcguy Mar 15 '19 at 21:32