Introduction:
When working with batch Apex in Salesforce, incorporating HTTP callouts can provide powerful integration capabilities. However, there are certain considerations and limitations that need to be addressed. In this guide, we will explore the steps to enable HTTP callouts in a batch Apex class and discuss important factors to keep in mind to ensure successful execution. Let's dive in!
Enabling HTTP Callouts with Database.AllowsCallouts Interface:
To execute HTTP callouts within a batch Apex class, it is essential to implement the Database.AllowsCallouts interface. Failure to do so will result in an error message stating "callout not allowed." By implementing this interface, you grant permission for callouts to be made during the batch execution.
Managing Callout Limits:
It's important to be mindful of the callout limit imposed by Salesforce. In a single transaction of a batch class, you can make up to 100 callouts. Exceeding this limit will result in the error message "System.LimitException: Too many callouts: 101" when attempting to perform the 101st callout. Therefore, it is crucial to consider the callout limit while designing your batch class.
Optimizing Batch Size:
To ensure compliance with the callout limit, it is recommended to keep the batch size below 100. By reducing the batch size, you can control the number of callouts made within a single transaction. Carefully consider your business requirements and data volume to determine an optimal batch size that balances efficiency and callout limits.
Batch Class:
global class Batchcallout implements Database.Batchable<sObject>, Database.AllowsCallouts {
global String query = 'SELECT Id, name FROM account LIMIT 50’;
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> scope) {
String endpoint = 'endpoint URL';
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setHeader('Authorization', header);
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(endpoint);
req.setMethod('POST');
for (Contact cont : scope) {
req.setBody(‘your ‘inputs);
res = http.send(req);
String JsonBody = res.getBody();
System.debug('Str: ' + res.getBody());
}
}
global void finish(Database.BatchableContext BC) {}
}
Conclusion:
Enabling HTTP callouts in a batch Apex class expands the integration capabilities of your Salesforce application. By implementing the Database.AllowsCallouts interface and managing callout limits, you can seamlessly integrate with external systems and leverage the power of web services. Remember to design your batch size below 100 to avoid exceeding callout limits and encountering errors. With this knowledge, you can unlock the potential of HTTP callouts in batch Apex and enhance the functionality of your Salesforce solutions.