How to make HTTP Callout in Batch Apex class Salesforce

APEX

We have to implement the interface Database.AllowsCallouts in batch apex if we want to do callouts from batch apex.

if we do not use this then an error will populate “callout not allowed”. We can make 100 callouts in a transaction of batch class. So always remember about the callout limit in apex class. because there will populate an error “System.LimitException: Too many callouts: 101” about 100 callouts. So batch size should be always below 100.

Note: Total number of callouts (HTTP requests or Web services calls) is 100, that means if you have one callout in your execute method you can keep batch size as 100.

global class ContactApex implements Database.Batchable<sObject>,   Database.AllowsCallouts {
 
    global String query = 'SELECT Id, LastName FROM Contact  LIMIT 100';
      
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
     }
 
     global void execute(Database.BatchableContext BC, List<Contact> scope) {         
        String endpoint;        
    for(Contact cont : scope){
         try {                  
          HttpRequest req = new HttpRequest();
          HttpResponse res = new HttpResponse();
          Http http = new Http();
          endpoint = 'Your endpoint url';
          req.setHeader('Authorization', header);
          req.setHeader('Content-Type', 'application/json');
          req.setEndpoint(endpoint);
          req.setMethod('POST');
          req.setBody('details that's you want to send');
          res = http.send(req);
          String sJson = res.getBody();
          System.debug('Str:' + res.getBody());
          }
          catch (Exception e) {         
            System.debug('Error:' + e.getMessage() + 'Line no:' + e.getLineNumber() );           
          }
       }
    }   
 
    global void finish(Database.BatchableContext BC){}
}

Call Batch Class :

ContactApex httpBatch = new ContactApex();
Id batchJobId = Database.executebatch(httpBatch, 100);

link

Leave a Reply