SharePoint 2013 working with REST

28/08/2013

With SharePoint 2013, a lot of things are now possible through the REST API. This is nice for web developers, and it’s nice for quick solutions directly in the browser, e.g. against Office 365.

The following code sniplets require jquery, which is not installed per default in Office 365, but if you are using chrome there are handy plugins that can add a reference to jquery, e.g. jquery-injector. Alternatively you can just do the following from you developer console.
[js]
var script = document.createElement(‘script’); script.src = ‘//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.3.js’; script.type = ‘text/javascript’; document.getElementsByTagName(‘head’)[0].appendChild(script);
[/js]

With jquery loaded, you can read the items from a list with the following code:
[js]
jQuery.ajax({
url: "https://sjkpdemo.sharepoint.com/Access/_api/web/lists/getbytitle(‘test’)/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(d) {console.log(d);},
error: function() {console.log(‘fail’);}
});
[/js]
Worth mentioning is how the specific list is found by title, and how the X-RequestDigest is read for the DOM.

To insert an item in a list is a little more involved. In my example I have created a custom list ‘Test’ with the standard Title column and a Date column that I have called Date.
The first thing you need to do is to get the ListItemEntityTypeFullName, it can be done by a GET to the following URL:

https://sjkpdemo.sharepoint.com/Access/_api/lists/getbytitle('test')?$select=ListItemEntityTypeFullName

In the result look for ListItemEntityTypeFullName: “SP.Data.TestListItem”, with that we can construct our POST request, which will look like:
[js]
jQuery.ajax({
url: "https://sjkpdemo.sharepoint.com/Access/_api/web/lists/getbytitle(‘test’)/items",
type: "POST",
data: JSON.stringify({ ‘__metadata’: { ‘type’: ‘SP.Data.TestListItem’ },
‘Title’: ‘Test’, ‘Date’: new Date().toISOString()}
),
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(d) {console.log(d);},
error: function() {console.log(‘fail’);}
});
[/js]
And wolla now you can create list item’s on the fly directly from your javascript code.