SharePoint Online REST API: GET vs POST vs PUT vs DELETE vs PATCH

SharePoint Online REST API: GET vs POST vs PUT vs DELETE vs PATCH

3 comments

Loading

Today in this “SharePoint Online REST API” article we will learn about the basic understanding of REST API in SharePoint and will understand GET vs POST vs PUT vs DELETE vs PATCH in SharePoint online thru the CRUD operations in the SharePoint REST API. Throughout this tutorial we will focus on the below:

  • What is the SharePoint REST API?
  • What is the use of the REST API in SharePoint?
  • REST API HTTP methods – HTTP operations in SharePoint using REST API
  • What are GET POST PUT and DELETE requests in HTTP?
  • What is the difference between PUT POST and PATCH with examples?
  • SharePoint Online RESTful API
  • SharePoint REST API operations
  • CRUD operations in SharePoint using the REST API
  • GET SharePoint list items using the REST API
  • Add a new item to a SharePoint list using the REST API
  • Update a SharePoint list item using the REST API
  • Delete a SharePoint list item using the REST API
  • How to deal with “__metadata type sp.data.listitem”?
  • Use of ListItemEntityTypeFullName in the SharePoint REST API

What is the SharePoint REST API?

One of the most popular types of API is REST or, as they’re sometimes known, RESTful APIs. The REST API is a data-centric web service based on the Open Data Protocol or OData. The way these web services work, and use each resource in the system is addressed by a specific URL that you pass on to the server. SharePoint 2013 has a REST API that exposes plenty of information about sites, users, lists and document libraries, etc.

The REST API (Representational State Transfer) service in SharePoint 2013  is another client object model technique like CSOM, JSOM, etc. which we used to do earlier.

REST – Representation State Transfer.

API – Application Programming Interface.

Example to Get data:

$. ajax ({  

url: URL, //This is the ENDPOINT URL
method: "GET", 

headers: {"Accept": "application/JSON; odata=verbose"},   
success: function (data) { 
console.log (data.d. email) //GET operation results will be here !!!
} 

}); 

SharePoint REST API – What is the use of rest API in SharePoint?

One of the key advantages of REST APIs is that they provide a great deal of flexibility. Data is not tied to resources or methods, so REST can handle multiple types of calls, and return different data formats. When we want the universal presence with minimum effort, given the fact that REST APIs are exposed as an HTTP Service, which is virtually present on almost all the platforms. Using REST API remotely we can interact with SharePoint 2013/2016/2019/Online sites and can perform Create, Read, Update, and Delete(CRUD) operations.

Few notes about REST API:

  • It is usually simple to build and adapt.
  • Low use of resources.
  • Process instances are created explicitly.

Read AlsoTop 5 SharePoint Online Authentication Methods You Need to Know About

REST API HTTP methods example (HTTP operations in SharePoint using REST API): SharePoint REST API

We can perform the below HTTP operation in SharePoint using REST API:

GET, POST, PUT, MERGE, and PATCH these methods are responsible for CREATE, READ, UPDATE, and DELETE (REST CRUD) operation in SharePoint.

In simple understanding we can define it as below:

GET:  GET method is used to retrieve or get the information from the given server using a given URI i.e Uniform Resource Identifier. When we use GET request only the data gets retrieved and in REST CRUD, it performs the READ operation.

POST: POST is used for sending the data to the server i.e uploading a file or transferring some data or adding a new row to the back end table to any kind of web form. POST is nothing but inserting new items in the backend server – in REST CRUD, it performs the CREATE operation.

PUT:  PUT is used for replacing the new data with existing data at the target resource.

What is the difference between POST, PUT, and PATCH methods of an HTTP protocol?

POST

An HTTP.POST method always creates a new resource on the server. It’s a non-idempotent request, i.e. if a user hits the same requests 2 times it would create another new resource if there is no constraint.

http post method is like a INSERT query in SQL which always creates a new record in database.

Example: We can use the POST method in scenarios like saving new users, sales orders, purchase orders, etc. where the backend server decides the resource id for the new resource.

PUT

In HTTP.PUT method, the resource is first identified by the URL and if it exists, then it is updated, otherwise, a new resource is created. When the target resource exists, it overwrites that resource with a completely new body. That is HTTP.PUT method is used to CREATE or UPDATE a resource.

http put method is like a MERGE query in SQL which inserts or updates a record depending upon whether the given record exists.

A PUT request is idempotent i.e. hitting the same requests twice would update the existing record (no new record will be created). In the PUT method, the resource id is decided by the client and provided in the request URL.

Example: Use the PUT method to update existing users, Sales Oder, Purchase orders, etc.

PATCH

An HTTP.PATCH method is used for partial modifications to a resource i.e. delta updates.

http patch method is like a UPDATE query in SQL which sets or updates selected columns only and not the whole row.

Example: We could use the PATCH method to update any status column like document life cycle status, approval status, migration status, and update certain columns in a SharePoint list or library, etc.

PATCH /api/users/80130625/PO/6027464

Request Body: {status: ‘Delivered’}

REST API endpoint URL SharePoint: SharePoint REST API

SP URL endpoint Description Supported HTTP Method
/_api/Web/Lists Retrieving all lists in a site and adding new lists to the site. GET, POST
/_api/Web/Lists/GetByTitle(‘listname’) Getting list details by the list title and updating it as well. If anyone changes the list title, the existing code will break. GET, POST
/_api/Web/Lists(guid’guid id of your list’) Same as above but changing the list title will not affect the code. This is an advantage over the other method. GET, POST
/_api/Web/Lists/GetByTitle(‘ listname ‘)/Fields Retrieve all fields/columns associated with a list and add new fields to the list. GET, POST
/_api/Web/Lists/GetByTitle(‘listname’)/Fields/GetByTitle(‘fieldname’) Getting details of a field, will be used in modifying and deleting fields. GET, PUT, PATCH, MERGE, DELETE
/_api/Web/Lists/GetByTitle(‘listname’)/Items Retrieving all items in a list and adding new items to the list. GET, POST
/_api/web/lists/GetByTitle(‘listname’)/GetItemById(itemId) This endpoint can be used to get, update and delete a single item – it works on a particular item based on its ID. GET, PUT, PATCH, MERGE, DELETE

SharePoint Online RESTful API: SharePoint online REST API

Below is the list of other useful SharePoint online RESTful API, that are frequently used in our daily SharePointing life:

Site Information API:

Endpoint URL: http://server/site/_api/Web/SiteUserInfoList

Users Information API:

Group Information API:

LISTS Information API:

SharePoint REST API operations: SharePoint online REST API

In order to perform the REST API operations like GET, POST in the SharePoint list, we need to have a setup of the SharePoint test list. Here I have created a list “SPRESTAPILearning” and below are my columns where almost all types of columns I have created.

SharePoint REST API
SharePoint REST API

And I have also created the below list which is used in the above “RESTLookup” column.

SharePoint REST API Lookup column
SharePoint REST API

Now we will try to hit the above list to get the data from SharePoint.

GET SharePoint list items using the REST API: SharePoint online REST API

GET all Items From SharePoint List – “SPRESTAPILearning”

Using the below code we can get SharePoint list items using the REST API.

function getSPListItems(webUrl,listTitle) { $.ajax( { url: webUrl + /_api/Web/Lists/GetByTitle('"+listTitle+"')/Items, type: "GET", headers:  { "accept": "application/json;odata=verbose", }, success: function (data) { console.log(data.d.results); //GET operation results will be here!!!  }, error: function (error) { alert(JSON.stringify(error)); } }); }

Note: In the above “webUrl” should be absolute URL which is _spPageContextInfo.webAbsoluteUrl

Example:

Now, let’s hit the below URL in the browser:

https://globalsharepoint2019.sharepoint.com/sites/SharePointRND/_api/Web/Lists/GetByTitle('SPRESTAPILearning')/Items

We will get all the items from “SPRESTAPILearning” list as a result.

Get Items from SharePoint List Using REST API
SharePoint REST API

Read AlsoThe Ultimate Postman Tutorial: A Beginner’s Guide to REST API Testing step by step

Add a new item to the SharePoint list using the REST API: SharePoint REST API

Adding New Item to SharePoint list using the HTTP POST method, using the below code we can add a new item to a SharePoint list using the REST API.

function AddNewItemToSPList(siteUrl,listTitle, itemProperties, success, failure) {

    var itemType = getItemTypeForListName(listName);
    itemProperties["__metadata"] = { "type": itemType };

    $.ajax({
        url: siteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(itemProperties),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data.d);
        },
        error: function (data) {
            failure(data);
        }
    });
}


// Get List Item Type metadata
function getItemTypeForListName(name)
 {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

 

In the header, we have to specify the value of “X-RequestDigest“. It’s a hidden field inside each web page, we will get, we can get its value by the above-mentioned way ($(“#__REQUESTDIGEST”).val()). But often, it does not work. So the appropriate approach is to get it from /_api/contextinfo. For this, we have to send an HTTP POST request to this URL (_api/contextinfo) and it will return “X-RequestDigest” value (in the JSON result, its name should be FormDigestValue).

Note:

In the above example properties of data are the internal names of the fields. We can get it from the following URL by making an HTTP GET request.

Syntax: "Site URL"+"/_api/Web/Lists/GetByTitle('ListTitle')/Fields?$select=Title,InternalName&$filter=ReadOnlyField eq false";

Example:

https://globalsharepoint2019.sharepoint.com/sites/SharePointRND/_api/Web/Lists/GetByTitle('SPRESTAPILearning')/Fields?$select=Title,InternalName&$filter=ReadOnlyField%20eq%20false

How to deal with “__metadata type sp.data.listitem” or how to pass the “__metadata” value?

We need to pass the “__metadata” value as below:

__metadata: {'type': 'SP.Data.' + 'Internal Name of the list' + 'ListItem'}

 

How to get the internal name of the list thru REST API?

We can get the list internal name directly thru the list setting page or from the below REST API:

Syntax: "Site URL"+/_api/Web/Lists/getbytitle('List Title')/ListItemEntityTypeFullName

Example:

https://globalsharepoint2019.sharepoint.com/sites/SharePointRND/_api/Web/Lists/GetByTitle('SPRESTAPILearning')/ListItemEntityTypeFullName
Get SharePoint List Internal Name By REST API
Get SharePoint List Internal Name By REST API

Update SharePoint list item using the REST API: SharePoint REST API

Using the below code we can update a SharePoint list item using the REST API.

function UpdateSPListItem(listTitle)
 {  
         
        var apiEndPoint = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getbytitle('"+listTitle+"')/items/getbyid(1)";  
        $.ajax({  
                url: apiEndPoint,  
                type: "POST",  
                headers: {  
                    Accept: "application/json;odata=verbose"  
                },  
                data: "{__metadata:{'type':'SP.Data.listInternalNameListItem'},
                 Title:"Updated Title"  
            }",  
            async: false, success: function(data) {  
                alert("Item has been updated successfully");  
            }, eror: function(data) {  
                console.log("An error occurred.Please try again");  
            }  
        });  
}  
}  

Delete SharePoint list item using the REST API – SharePoint REST API

Using the below code we can delete the SharePoint list item using the REST API.

function DeleteSPListItem(listTitle itemIdToDelete)
 {  
    
        $.ajax({  
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemIdToDelete + ")",  
            type: "POST",  
            contentType: "application/json;odata=verbose",  
            headers: {  
                "Accept": "application/json;odata=verbose",  
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
                "IF-MATCH": "*",  
                "X-HTTP-Method": "DELETE",  
            },  
            success: function(data) {  
                alert("Item has been successfully deleted");  
            },  
            error: function(data) {  
                alert("Due to error failed to delete the item");  
            }  
        });  
     
} 

Read AlsoIn 4 steps access SharePoint online data using postman tool

Summary: SharePoint REST API (REST API HTTP methods example)

Thus, in this article we have learned the below:

  • What is the SharePoint REST API?
  • What is REST — A Simple Explanation
  • What is the use of the REST API in SharePoint?
  • Understanding the basics of RESTful APIs
  • REST API HTTP methods – HTTP operations in SharePoint using the REST API
  • What is GET POST PUT and DELETE requests in HTTP?
  • What is the difference between PUT POST and PATCH with examples?
  • SharePoint Online RESTful API
  • SharePoint REST API operations
  • CRUD operations in SharePoint using the REST API
  • GET SharePoint list items using the REST API
  • Add a new item to the SharePoint list using the REST API
  • Update SharePoint list item using the REST API
  • Delete SharePoint list item using the REST API
  • How to deal with “__metadata type sp.data.listitem”?
  • Use of ListItemEntityTypeFullName in REST API

See Also: PowerApps tutorial for beginners

Looking for a PowerApps tutorial from scratch? Then you are in the right place, below are a bunch PowerApps articles you may like:

Buy the premium version of SharePoint Online & Office 365 administration eBook from here:


Buy SharePoint Online & Office 365 Administration eBook

About Post Author

3 comments on “SharePoint Online REST API: GET vs POST vs PUT vs DELETE vs PATCH”

Do you have a better solution or question on this topic? Please leave a comment