How to make HTTP Callout in Batch Apex class Salesforce

by Rijwan Mohmmed
0 comment
how-to-make-http-callout-in-batch-apex-class-salesforce

To call an HTTP callout in batch Apex, we need to implement Database.AllowsCallouts interface in the class. 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.

HttpBatchApex.cls :

global class HttpBatchApex 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('Information you wanna 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 :

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

You may also like

Leave a Comment