Background


This articles shows an object-oriented approach on Basic SharePoint REST API CRUD Operations using Javascript.

The functions used in this library uses JSON Light to minimize the payload size on your REST API Calls. This feature may not be enabled on your environment by default. To enable this please see [How to turn on and off the multiple metadata formats for JSON in SharePoint Server 2013].


Get List Items

This function will retrieve items of a list. You can use the queryStr parameter to filter/sort your result. Sample implementation below.
If you notice on the headers, odata is set to nometadata which means the JSON result will only include the column values hence payload will be lighter.

var myutil = {}
 
myutil.getListItems = function (listTitle, queryStr) {
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listTitle + "')/Items?";
    if (typeof (queryStr) !== "undefined") {
        url += queryStr;
    } else {
        url += "$top=1000";
    }
 
    return $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json;odata=nometadata" },
        async: true
    }).fail(function (jqXHR, textStatus) {
        alert("Failed to request list '" + listTitle + "'. status:" + textStatus);
        if (console) {
            console.log(jqXHR);
        }
    });
}

Sample Implementation

var myClass = {}
 
myClass.loadClass = function () {
    var deferred = $.Deferred();
    var query = "$orderby=Date%20desc&$select=Id,Title,Created,Date,Description";
    myutil.getListItems("My Class", query).done(function (data) {
        deferred.resolve(data);
    });
    return deferred.promise();
}


Create List Item

This function will insert an item to your list. The item parameter contains the column values for your list item. You should include all SharePoint required fields. This uses minimalmetadata to minimize the payload on your REST API Call, nometadata will not work. (Same goes for Update and Delete)

//Create list item
myutil.createListItem = function (listTitle, item) {
    var digestValue = $("#__REQUESTDIGEST").val();
    return $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/Items",
        type: "POST",
        data: JSON.stringify(item),
        async: false,
        headers: {
            "Accept": "application/json;odata=minimalmetadata",
            "content-Type": "application/json;odata=minimalmetadata",
            "X-RequestDigest": digestValue
        },
        success: function (data) {
            console.log(data);
        },
        error: function (error) {
            console.log(error);
        }
    });
}

Sample Implementation

myClass.insertClass= function (title, date, background) {
    var itemType = "SP.Data.My_x0020_ClassListItem";
    var item = {
        "odata.type": itemType,
        "Title": title,
        "Date":date,
        "Description": background,
    };
    return myutil.createListItem("My Class", item);
}

Update List Item

This function will update an item on your list. The item parameter contains the column values for your list item. Include only the columns you want to update. The itemID parameter is the list item ID of the item you want to update.

//Update list item
myutil.updateListItem = function (listTitle, item, itemID) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('" + listTitle + "')/Items(" + itemID + ")",
        type: "POST",
        contentType: "application/json;odata=minimalmetadata",
        data: JSON.stringify(item),
        async: true,
        headers: {
            "Accept": "application/json;odata=minimalmetadata",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "MERGE",
            "If-Match": '*'
        },
        success: function (data) {
            console.log(data);
        },
        error: function (error) {
            console.log(error);
        }
    });
}

Sample Implementation

myClass.updateClass = function (itemID, title, date, background) {
    var itemType = "SP.Data.My_x0020_ClassListItem";
    var item = {
        "odata.type": itemType,
        "Title": title,
        "Date": date,
        "Description": background,
    };
    myutil.updateListItem("My Class", item, itemID);
}



Delete List Item

This function will update an item on your list. The itemID parameter is the list item ID of the item you want to delete.

//Delete list item
myutil.deleteListItem = function (listTitle, itemID) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('" + listTitle + "')/Items(" + itemID + ")",
        type: "POST",
        headers: {
            "Accept": "application/json;odata=minimalmetadata",
            "X-Http-Method": "DELETE",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "If-Match": "*"
        },
        success: function (data) {
            console.log(data);
        },
        error: function (error) {
            console.log(error);
        }
    });
}

Sample Implementation

myClass.deleteClass = function (itemID) {
    myutil.deleteListItem("My Class", itemID);
}


You can download the utility JS here.