Tuesday 30 July 2019

Rest API Services

REST – Representation State Transfer.


  1. SharePoint can be integrated using REST API
  2. OData query operators supported in the SharePoint REST service
  3. There are so many ways but the approach is almost same everywhere. 
  4. jQuery($.ajax) will be used to access all endpoints
  5. Returns JSON format collection of the results


Powerful solution is using the $filter key.
/_api/web/lists/getbytitle('listname')/Items?$select=Title&$filter=Title eq 'example 1'

Multiple $filter keys + values
/_api/web/lists/getbytitle('listname')/Items?$select=Title&$filter=((Title eq 'example 1') or (Title eq 'example 2'))

For Paging
/_api/web/lists/getbytitle('listname')/Items?$top='10'&$skip='20'


Get a single list item


Function getListItem(url, listname, id, complete, failure) {
 // Getting our list items

$.ajax({
  url: _spPageContextInfo.webAbsoluteUrl + "/_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);
  }
  });
 }

}

Refer the link
link

How to get more than 5000 items by Rest API?

Here we are doing recursive call to the GetListItems() function. This will fetch data in the bunch of 1000 items and concat it to response variable.

var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DocumentList')/items?$select=customerID&$top=1000";
    var response = response || [];  // this variable is used for storing list items
    function GetListItems(){
        return $.ajax({
            url: url,  
            method: "GET",  
            headers: {  
                "Accept": "application/json; odata=verbose"  
            },
            success: function(data){
                response = response.concat(data.d.results);
                if (data.d.__next) {
                    url = data.d.__next;
                    GetListItems();
                }
                $.each(response, function(index, item) {
                    arrayCustomerID[index] = item.customerID;
                });
            },
            error: function(error){
            }
        });
    }
if (data.d.__next) will enter loop only if item number is 1001.
data.d.__next contains the url to get the next items. In case we don't have more items left to fetch, it will not call GetListItems() function.


What is formDigest in REST API?

If you aren't using OAuth to authorize your requests and when creating, updating, and deleting SharePoint entities
these operations require the server's request form digest value as the value of the X-RequestDigest header

jQuery.ajax({
        url: "http://<site url>/_api/web/lists",
        type: "POST",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true,
 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }
),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "content-length": <length of post body>,
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: doSuccess,
        error: doError
});

Rest API Filtering:
Filter by Title

 /_api/web/lists/getbytitle('infolist')/items?$filter= Employee eq ‘parth'

Filter by ID:  

/_api/web/lists/getbytitle('infolist')/items?$filter=ID eq 2

Filter by Date

  /_api/web/lists/getbytitle('infolist')/items?$filter=Start_x0020_Date le datetime'2016-03-26T09:59:32Z'

Multiple Filters

  /_api/web/lists/getbytitle('infolist')/items?$filter=( Modified le datetime'2016-03-26T09:59:32Z') and (ID eq 2)

Title name starts with the letter P

/_api/web/lists/getbytitle(‘'infolist')/items?$filter=startswith(Title,‘P’)

Return all items from the'infolist'list modified in May


/_api/web/lists/getbytitle(‘'infolist')/items? $filter=month(Modified) eq 5

Retrieve all sites and all subsites from the SharePoint REST API

var url = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/webs";

Retrieve current login user

Step-1

url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentUser",

Step-2

var userid = _spPageContextInfo.userId;

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";


Difference between PUT, PATCH, MERGE?

1. PATCH and MERGE works same but the method PUT is different. 
2. If we need to update only one field in the list item, we will have to go for PATCH or MERGE 
3. because the PUT method will require all the fields in the data variable to update.



How to get More than 5000 items in sharepoint by Rest API ?


1. We can call  recursive call to the GetListItems() function
2. This will fetch data in the bunch of 1000 items and concat it to response variable.
3. call  data.d.__next;



var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DocumentList')/items?$select=customerID&$top=1000";
    var response = response || [];  // this variable is used for storing list items
    function GetListItems(){
        return $.ajax({
            url: url,  
            method: "GET",  
            headers: {  
                "Accept": "application/json; odata=verbose"  
            },
            success: function(data){
                response = response.concat(data.d.results);
                if (data.d.__next) {
                    url = data.d.__next;
                    GetListItems();
                }
                $.each(response, function(index, item) {
                    arrayCustomerID[index] = item.customerID;
                });
            },
            error: function(error){
            }
        });
    }

No comments:

Post a Comment