[SalesForce] Sending batch rest api request from apex

I need to get multiple data from salesforce. To get the resource i call the endpoint as shown below.

public String getData(Id docId) {
        HttpRequest request = new HttpRequest();
        request.setEndpoint(baseURL + '/services/data/v42.0/connect/files/+'docId');
        request.setMethod('GET');
        request.setHeader('Authorization', 'Bearer '+UserInfo.getSessionId());
        request.setHeader('X-Connect-Bearer-Urls', 'true');

        Http http = new Http();
        HttpResponse response = http.send(request);
     }
String data1 = getData(abcdef);
String data2 = getData(lklsdk);

Now, Instead of calling getData() method twice and calling the rest endpoint twice, i am trying to use batch rest api.

SO, i changed the endpoint as:

request.setEndpoint(baseURL + '/services/data/v42.0/connect/files/batch/+docId1+','+docId2);

Unfortunately, when i run the send the above request, I get invalid session Id issue but if i call the endpoint multiple times by removing batch (as shown in above function), i get correct response.

So, how do i resolve send multiple ids using batch rest api?

Best Answer

Rolling up comment to an answer if it helps someone in similar situation.

I tried getting details of multiple files using the API mentioned in the question and was able to successfully get response. My request url looked like:

https://myinstance.my.salesforce.com/services/data/v42.0/connect/files/batch/xxxid1,yyyid2

Using a stale access token, I received invalid session id as expected.

[
    {
        "message": "Session expired or invalid",
        "errorCode": "INVALID_SESSION_ID"
    }
]

However, when I tried with a new access token, I was able to get the response (sample response below, removed all other details).

{
"hasErrors": false,
"results": [
    {
        "result": {
            "downloadUrl": "/services/data/v42.0/connect/files/xxxid1/content?versionNumber=1",
            "id": "xxxid1",
        },
        "statusCode": 200
    },
    {
        "result": {
            "downloadUrl": "/services/data/v42.0/connect/files/yyyid2/content?versionNumber=1",
            "id": "yyyid2",
        },
        "statusCode": 200
    }
]
}

Based on your comment above:

I had to clear all chrome history, caches e.t.c. I waslogged into salesforce in chrome and i got the above error but when i logged into salesforce using mozilla, no error was thrown

The root cause here seemed to be the access token. Using the correct access token worked fine.

Related Topic