SharePoint 2013 – CRUD on List Items Using REST Services & jQuery

What’s New

SharePoint 2013 has greatly expanded the REST services available to developers.  With this, we have much more SharePoint functionality exposed via CSOM and Web Services. Also, all of the new REST Services use the ODATA standards (more Information on that Here). This means that we can easily test our queries using the browser, because we’ll be executing standard GET requests.
This means, that going forward, we’re going to see the old .asmx SOAP services disappear.
One of the most fundamental REST services is the set that allow us to interact with List Items in SharePoint 2013.  Before we get into performing our CRUD Operations using jQuery, let’s go over their basic use.

REST Services – High Level Overview

Let’s start out with our basic get commands in REST. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.
Command URL
 Get All Lists http://server/site/_api/lists
 Get All List Items From a Single List http://server/site/_api/lists/getbytitle(‘listname’)/items
 Get a Single List Item http://server/site/_api/lists/getbytitle(‘listname’)/items
 Get Back Certain Columns http://server/site/_api/lists/getbytitle(‘listname’)/items?$select=Title,Id
 Order Your Results  http://server/site/_api/lists/getbytitle(‘listname’)/items?$orderby=Title
So, how do we test our SharePoint 2013 REST GET queries?  Just paste the URL into your browser and the XML will be returned.
However, IE10 doesn’t like to display it by default so I would recommend using Chrome / FireFox with an addon that makes reading XML easier.  So, start learning by manipulating your REST urls in the browser and testing out all of the features.

Making SharePoint 2013 REST Service Calls with jQuery

What You’ll Need to Know

Before we get to our CRUD Operations, there are a few basic functions we’ll need to use to get additional data for use later on.  The Item Type in particular is nothing crazy, just a string manipulation used to build the item type which is based on the title of the list, but it’s case sensitive so we have a function to ensure we capitalize it.

Get a Single List Item

function getListItem(url, listname, id, complete, failure) {
 // Getting our list items
 $.ajax({
  url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
  method: "GET",
  headers: { "Accept": "application/json; odata=verbose" },
  success: function (data) {
   // Returning the results
   complete(data);
  },
  error: function (data) {
   failure(data);
  }
  });
 }
}
Get the Item Type (used in Updates / Creates)
// Getting the item type for the list
function getListItemType(name) {
    return"SP.Data." + name[0].toUpperCase() + name.substring(1) + "ListItem";
}

REST Services – Get List Items

Getting List Items using the SharePoint REST Services is probably the simplest operation of them all.  An example of how to do this is below:
// Getting list items based on ODATA Query
function getListItems(url, listname, query, complete, failure) {

    // Executing our items via an ajax request
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (data) {
            failure(data);
        }
    });

}

REST Services – Create Items

Creating list items gets a little bit tricky, because you’ll need a few key pieces of information:
  • The List Item type
  • REQUESTDIGEST value to prevent replay attacks
  • An object containing your List Item Values
// Adding a list item with the metadata provided
function addListItem(url, listname, metadata, success, failure) {

    // Prepping our update
    var item = $.extend({
        "__metadata": { "type": getListItemType(listname)}
    }, metadata);

    // Executing our add
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data); // Returns the newly created list item information
        },
        error: function (data) {
            failure(data);
        }
    });

}

REST Services – Update List Items

Updating list items is very similar to the task of creating list items when using jQuery Ajax calls.  You’ll need the same information you used then you created your list item, with one more piece of information:
  • The List Item Type
  • REQUESTDIGEST
  • An object containing your List Item Values & Item Type
  • The REST URL to your List Item (We use our getListItem function to get this reliably, See Above)
    • Stored in: data.d.__metadata.uri
function updateListItem(url, listname, id, metadata, success, failure) {

    // Prepping our update
    var item = $.extend({
        "__metadata": { "type": getListItemType(listname) }
    }, metadata);

    getListItem(url, listname, id, function (data) {
        $.ajax({
            url: data.d.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.d.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });

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

}

REST Services – Delete List Items

Deleting a list item also requires the REST URL that leads to the List Item you would like to delete.  Again, we get this through our getListItem function (See Above).  So you’ll need:
  • The List Item Type
  • REQUESTDIGEST
  • REST URL to your List Item (via our getListItem function)
// Deleting a List Item based on the ID
function deleteListItem(url, listname, id, success, failure) {

    // getting our item to delete, then executing a delete once it's been returned
    getListItem(url, listname, id, function (data) {
        $.ajax({
            url: data.d.__metadata.uri,
            type: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-Http-Method": "DELETE",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "If-Match": data.d.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    });

};

Practical Application

I’ve spoken with many people who are apprehensive about using JavaScript / jQuery for full applications. However, with the amount rich, client-side applications users are working with steadily growing, the average user has come to expect them.
So, I would recommend getting started creating your own JavaScript / jQuery applications as soon as possible.  SharePoint 2013 is moving that way at a rapid pace.

Comments