Pages

Monday, May 8, 2017

SharePoint REST API getting all list items


SharePoint Online allow us to read list items with help of JavaScript Client side Object modal. There are two REST API services available to read the items as explained below,

I. REST API: /_api/web/lists/GetByTitle('ListName')/items
Below is the code snippet to read list items,

function getListItems(){
var output = [];
    var endpoint = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/GetByTitle('Configurations')/items";   
    $.when($.ajax({
        url: endpoint,
 method: "GET",
 async:false,
 headers: { 
  "X-RequestDigest": $("#__REQUESTDIGEST").val(),
       "Accept": "application/json; odata=verbose",
       "Content-Type": "application/json; odata=verbose"
  },
 success: function (data) {      
 
 },
 error: function (data) {
 }
    })).done(function(data) {        
    });
    return output;

}

Above method only returns top 100 items and cannot read all items of list more than 100. To get all list items without limit use 2nd approach below.

II. REST API: /_api/web/lists/GetByTitle('ListName')/GetItems
Below is the code snippet to read list items,

function getListItems()
{
var output = [];
var pageslib = getPagesLib();
    var endpoint = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Configurations')/GetItems";
    var requestData = { "query" :
           {"__metadata": 
              { "type": "SP.CamlQuery" }
              , "ViewXml": "
"           }
        };
    $.when($.ajax({
        url: endpoint,
 method: "POST",
 async:false,
 data: JSON.stringify(requestData),
 headers: { 
  "X-RequestDigest": digval,
           "Accept": "application/json; odata=verbose",
           "Content-Type": "application/json; odata=verbose"
  },
 success: function (data) {  
 },
 error: function (data) {
  debugger;
 }
    })).done(function(data) {        
    });
    return output;

}
Above function returns all list items without any limit. You can modify 'ViewXml' attribute to apply CAML Query to filter/sort the items. digval is the form digest value need to generate based on current site context. Please search my blog for code to get form digest value dynamically.

No comments:

Post a Comment