function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Patrick Gaspersz 2Patrick Gaspersz 2 

API call in batchable

I'm performing a API call. When running the call in outside a Batchable class the API call is performed withoud problems (for example in Execute Anonymous) . However the exact same call results in a error "INVALID_SESSION_ID" when part of a Batchable Class.

Even when passing the SessionId to the batchable class the error remains. Example code profided below. Does anybody have a solution or idea why the call fails within a Batchable class?

Example code:
public class AutoCreateRelationVisit implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
    
    private String sesId;
    
    public AutoCreateRelationVisit(){
        this(UserInfo.getSessionId());
    }
    
    public AutoCreateRelationVisit(String sesId){
        this.sesId = sesId;
    }

    public Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'Select Id FROM MaintenancePlan'; //LIMIT toevoegen
        return Database.getQueryLocator(query);
    }
    
    public void execute (Database.BatchableContext BC, List<MaintenancePlan> scope) {
        String salesforceHost = System.Url.getSalesforceBaseURL().toExternalForm();
        String url = salesforceHost + '/services/data/v40.0/actions/standard/generateWorkOrders';
        
        // Create HTTP request
        HttpRequest request = new HttpRequest();
        request.setEndpoint(url);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=UTF-8');
        request.setHeader('Authorization', 'OAuth ' + this.sesId);
        
        //List<MaintenancePlan> mpList=new List<MaintenancePlan>(); use this when updating the MaintenancePlan in next step
        
        //for (MaintenancePlan mp : scope) {
              //Set the body as . JSON object
              string jsonBody = '{"inputs" : [{"recordId" : "1MP260000000006GAA"}]}';
            system.debug(LoggingLevel.Error, 'Json Body' + jsonBody);
            request.setBody(jsonBody);
            Http http = new Http();
            HttpResponse response = http.send(request);
            system.debug(LoggingLevel.Error, response.getBody());
            // Parse the JSON response
            
            if (response.getStatusCode() != 201) {
                System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
            } else {
                System.debug(response.getBody());
            }
       // }
    }
    public void finish(Database.BatchableContext jobId) {}
}
Best Answer chosen by Patrick Gaspersz 2
NArendra NimmanaNArendra Nimmana
change the following line as request.setHeader('Authorization', 'OAuth ' + this.sesId);
this request.setHeader('Authorization', 'OAuth ' + sesId);

All Answers

NArendra NimmanaNArendra Nimmana
I think the problem is with this.sesId 
try to use sesId Instead of this.sesId and let me Know.
Thanks Narendra.
NArendra NimmanaNArendra Nimmana
change the following line as request.setHeader('Authorization', 'OAuth ' + this.sesId);
this request.setHeader('Authorization', 'OAuth ' + sesId);
This was selected as the best answer
Patrick Gaspersz 2Patrick Gaspersz 2
Thanks NAerendra,

Very sharp of you. I had problems with generated Session Id within the Batchable. To compensate this we decided to pass the Session Id in a variable. I fully forgot to reference this variable in the correct manner. Now the call finnaly works. Thanks.