Sharepoint - How to get all items in a view using REST API

The following example demonstrates how to retrieve list items for a View using SharePoint REST:

function getListItems(webUrl,listTitle, queryText) 
{
    var viewXml = '<View><Query>' + queryText + '</Query></View>';
    var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems"; 
    var queryPayload = {  
               'query' : {
                      '__metadata': { 'type': 'SP.CamlQuery' }, 
                      'ViewXml' : viewXml  
               }
    };
    return executeJson(url,"POST",null,queryPayload);
}


function getListViewItems(webUrl,listTitle,viewTitle)
{
     var url = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
     return executeJson(url).then(
         function(data){         
             var viewQuery = data.d.ViewQuery;
             return getListItems(webUrl,listTitle,viewQuery); 
         });
}

where

function executeJson(url,method,headers,payload) 
{
    method = method || 'GET';
    headers = headers || {};
    headers["Accept"] = "application/json;odata=verbose";
    if(method == "POST") {
        headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
    }      
    var ajaxOptions = 
    {       
       url: url,   
       type: method,  
       contentType: "application/json;odata=verbose",
       headers: headers
    };
    if (typeof payload != 'undefined') {
      ajaxOptions.data = JSON.stringify(payload);
    }  
    return $.ajax(ajaxOptions);
}

Usage

getListViewItems(_spPageContextInfo.webAbsoluteUrl,'Tasks','All Tasks')
.done(function(data)
{
     var items = data.d.results;
     for(var i = 0; i < items.length;i++) {
         console.log(items[i].Title);
     }    
})
.fail(
function(error){
    console.log(JSON.stringify(error));
});

Using REST you can't get items from a view. For that you have two options

  1. Get the view fields and form a query
  2. Create a CAML query and use it to get the items.

https://social.msdn.microsoft.com/forums/sharepoint/en-US/a5815727-925b-4ac5-8a46-b0979a910ebb/query-listitems-by-view-through-rest-api

Tags:

Rest

List View