Here is a little tip that will save you hours of head scratching.
See there are two ways to update data in SharePoint using REST based API.
- A PUT request is used to update an entire entity. If no values are specified for fields in the entity, the fields will be set to default values.
- A MERGE request is used to update only those field values that have changed. Any fields that are not specified by the operation will remain set to their current value.
Now, sit back and think about it. You are going to update the entire entity! Hmm. Which means, you need to a) specify every column value, and b) ensure that the read only values match what was supplied to you. What a pain in the donkey! So 99/100 times, a PUT request will give you a HTTP 500 internal server error occurred, which is just so helpful.
Because of that, it is almost always easier to use a MERGE request, than a PUT request. But the trick here is that MERGE Isn’t an HTTP VERB like the below table extracted from MSDN seems to suggest,
Update (update all fields and use default values for any undefined fields)
Update (update only the fields that are specified and changed from current version)
Really? Well observe the following cod e-
1: var inputData = new Object();
2: inputData.TITLE = "New Title";
3: var etag = "W/\"1\"";
4: var Id = 1;
6: var request = new Sys.Net.WebRequest();
8: request.get_headers()['X-HTTP-Method'] = 'MERGE';
10: request.get_headers()['Accept'] = 'application/json';
11: request.get_headers()['Content-Type'] = 'application/json';
12: request.get_headers()['If-Match'] = etag;
As you can see above,
- MERGE is like a sub-method of POST. Denoted by X-HTTP-Method
- You must specify an If-Match, which is the etag value that you were returned when you queried for this data – this is for concurrency checks. You can pick the etag value at __metdata.etag of any entry in return values of a GET request.
- The above example uses ASPNET AJAX, you can very easily achieve the same using jQuery $.ajax. Just remember to,
- Add the X-HTTP-Method, and
- Add the etag,
- .. you can add both of these using the beforeSend method handler of $.ajax. You can read the dox, or may be a trillion $ to write it for you. But believe me, it’s easy, just try it yourself first.
Yeah, so that’s it. Have fun. Now you can easily update data, and what is cool is that
- This can do cross site collection updates – something the client object model cannot do.