Apex Batch – Use of interface Database.AllowsCallouts in Batch Class
Hello guys,
Today, I will talk about interface named as Database.AllowsCallout in Batch helps in integrate Salesforce with an external server. To use a callout in batch Apex, we must use an interface Database.AllowsCallouts in the class definition of batch class.
Syntax-
global class SearchAndReplace implements Database.Batchable<sObject>, Database.AllowsCallouts{ }
Let see a simple example on Database.AllowCallouts -
global class BatchWithCallout implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful { private final String clientId = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx’; private final String clientSecret = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx’; private final String username = ‘xxxxxxxxxxxxxxxxxxxxx’; private final String password = ‘xxxxxxx’; public Integer count=0; public String q = ‘Select ID, Name from Account LIMIT 10’; global Database.QueryLocator start(Database.BatchableContext BC) { return Database.getQueryLocator(q); } global void execute(Database.BatchableContext BC, List<Account> records) { count = count+1; String endpoint = ‘https://login.salesforce.com/services/oauth2/token’; for ( integer i = 0; i< records.size(); i++ ){ try { String reqbody = ‘grant_type=password&client_id=’+ clientId+’&client_secret=’+ clientSecret+’&username=’+ username+’&password=’+password; Http http = new Http(); HttpRequest request = new HttpRequest(); HttpResponse response = new HttpResponse(); request .setBody(reqbody); request .setMethod(‘POST’); request .setEndpoint(‘https://login.salesforce.com/services/oauth2/token’); response = http.send(req); request .setHeader(‘Authorization’, ‘header’); request .setHeader(‘Content-Type’, ‘application/json’); request .setEndpoint(endpoint); request .setMethod(‘POST’); request .setBody(‘Information you wanna send’); request .setCompressed(true); // This is imp according to SF, but please check if // the web service accepts the info. Mine did not 😛 // Had to set it to false if (!Test.isRunningTest()) { response = http.send(request); String sJson = response .getBody(); System.debug(‘@@@@Str:’ + response .getBody()); } // now do what u want to with response System.debug(‘@@@@execute’+count); } catch (Exception err) { System.debug(‘@@@@Error:’ + err.getMessage() + ‘LN:’ + err.getLineNumber() ); } } } global void finish(Database.BatchableContext BC){ System.debug(‘@@@@finish’+count); } }
Note:- If you don’t know what is Database.Stateful, Kindly read this blog.
Thanks.
Happy Coding.