0

Let suppose I have the following three sharepoint Rest APIs call, I want to merge them to one call for paging and sorting.

_api/Web/GetFolderByServerRelativeUrl('/emails24/1001')/Files _api/Web/GetFolderByServerRelativeUrl('/scaned/1001')/Files _api/Web/GetFolderByServerRelativeUrl('/lnked/1001')/Files Does anyone have any idea, how to achieve this.

Or any alternative way of doing this.

1 Answer 1

2

You can try the batch API as below:

SP.SOD.executeFunc("SP.RequestExecutor.js", "SP.RequestExecutor", function () {
    // create a new executor for the current web
    var executor = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
    // get a new Guid for the batch using the scripthelper utility
    var batchGuid = SP.ScriptHelpers.newGuid();
    // setup an array to hold strings that will be sent as the request body
    var batchContents = new Array();

    // build first request section against first call
    var endpoint = _spPageContextInfo.webAbsoluteUrl
        + "/_api/Web/GetFolderByServerRelativeUrl('/emails24/1001')/Files";

    batchContents.push("--batch_" + batchGuid);
    batchContents.push("Content-Type: application/http");
    batchContents.push("Content-Transfer-Encoding: binary");
    batchContents.push("");
    batchContents.push("GET " + endpoint + " HTTP/1.1");
    batchContents.push("Accept: application/json;odata=verbose");
    batchContents.push("");

    // build second request section against second call
    var endpoint = _spPageContextInfo.webAbsoluteUrl
        + "/_api/Web/GetFolderByServerRelativeUrl('/scaned/1001')/Files";

    batchContents.push("--batch_" + batchGuid);
    batchContents.push("Content-Type: application/http");
    batchContents.push("Content-Transfer-Encoding: binary");
    batchContents.push("");
    batchContents.push("GET " + endpoint + " HTTP/1.1");
    batchContents.push("Accept: application/json;odata=verbose");
    batchContents.push("");

    // build second request section against third call
    var endpoint = _spPageContextInfo.webAbsoluteUrl
        + "/_api/Web/GetFolderByServerRelativeUrl('/lnked/1001')/Files";

    batchContents.push("--batch_" + batchGuid);
    batchContents.push("Content-Type: application/http");
    batchContents.push("Content-Transfer-Encoding: binary");
    batchContents.push("");
    batchContents.push("GET " + endpoint + " HTTP/1.1");
    batchContents.push("Accept: application/json;odata=verbose");
    batchContents.push("");


    // end the request with `--batch_batchid--`
    batchContents.push("--batch_" + batchGuid + "--");

    // join the array contents to build a single batch body string
    var batchBody = batchContents.join("\r\n");

    executor.executeAsync({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/$batch",
        method: "POST",
        body: batchBody,
        headers: {
            "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
            "Content-Type": "multipart/mixed; boundary=batch_" + batchGuid
        },
        success: function (response) {
            console.log(response);
            var responseInLines = response.body.toString().split('\n');
            // read routine below courtesy of Andrew Connell: https://github.com/andrewconnell/sp-o365-rest/tree/master/SpRestBatchSample
            // read each line until you find JSON...
            for (var currentLine = 0; currentLine < responseInLines.length; currentLine++) {
                try {
                    // parse the JSON response...
                    var tryParseJson = JSON.parse(responseInLines[currentLine]);
                    console.log(tryParseJson.d.results);
                } catch (e) {
                    // don't do anything... just keep moving

                    // execution in this block just means we hit a 
                    // line in the response that was not valid JSON -JM
                }
            }
        },
        error: function (response) { console.log(response) }
    });
});

Reference - SPRestBatchsample

Basic batched request using REST

Datajs

You can also us the datajs library to batch calls as below:

var jsonSPHeaders = {  
    "Accept": "application/json;odata=verbose", 
    "Content-Type": "application/json;odata=verbose",
    "DataServiceVersion": "3.0" 
};

OData.request( {
    requestUri: _spPageContextInfo.webAbsoluteUrl + "/_api/$batch",
    method: "POST",
    headers: { "X-RequestDigest": $("#__REQUESTDIGEST").val(),
               "DataServiceVersion": "3.0" },
    data: { __batchRequests: [
       { requestUri: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/GetFolderByServerRelativeUrl('/emails24/1001')/Files", method: "GET" , headers: jsonSPHeaders },
       { requestUri: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/GetFolderByServerRelativeUrl('/scaned/1001')/Files", method: "GET" , headers: jsonSPHeaders },
       { requestUri: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/GetFolderByServerRelativeUrl('/lnked/1001')/Files", method: "GET", headers: jsonSPHeaders }
    ]}
},
function (data, response) {
    console.log('First data:');
    printListItems(data.__batchResponses[0].data);
    console.log('Second data:');
    printListItems(data.__batchResponses[1].data);
    console.log('Third data:');
    printListItems(data.__batchResponses[2].data);
}, 
null, 
OData.batchHandler);

function printListItems(data){
   data.results.forEach(function(item){
       console.log(item); 
   });
}
7
  • Great :) how would one achieve sorting and paging?
    – Pir Abdul
    Commented Dec 8, 2016 at 7:23
  • 1
    you can use $orderby to sort that data based on the field. To use paging, you can use $skip or $skiptoken=Paged=TRUE&p_ID=1. Check this link - SharePoint paging Commented Dec 8, 2016 at 8:41
  • got 404, when executing batch request - mysite/module/_api/$batch
    – Pir Abdul
    Commented Dec 8, 2016 at 12:24
  • is it SharePoint 2013 On prem environment ? Commented Dec 8, 2016 at 12:29
  • Yes, sharepoint 2013 on premises
    – Pir Abdul
    Commented Dec 8, 2016 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.