In certain scenarios, we need to make the webservice callout from the apex trigger to call an external webservice. We cannot call external web services synchronously from triggers, because calling a web service synchronously from triggers will hold up the database transaction until the callout completed. This will impact performance for other transactions. In this scenario we can invoke callouts from triggers by encapsulating the callouts in @future methods. Here is an example, how to invoke webservice callouts from trigger.
Apex Class:
public class LeadTriggerHandler {
@future (callout=true)
public static void sendLeadInfo(string firstName, string lastName, string email) {
try{
HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
Http http = new Http();
request.setEndpoint('Your Endpoint URL');
request.setHeader('Content-Type','application/json');
request.setMethod('POST');
request.setBody('fname='+EncodingUtil.urlEncode(firstName, 'UTF-8')+'&lname='+EncodingUtil.urlEncode(lastName, 'UTF-8')
'&email='+EncodingUtil.urlEncode(email, 'UTF-8'));
request.setCompressed(true);
response = http.send(request);
if (response.getStatusCode() == 200) {
System.debug('Response-' + response);
}
}
catch(System.CalloutException e){
System.debug('Error-' + e.getMessage());
}
}
}
Apex Trigger:
trigger LeadTrigger on Lead (after insert) {
for (Lead objLead : Trigger.new) {
//make webservice callout
LeadTriggerHandler.sendLeadInfo(objLead.FirstName, objLead.LastName, objLead.Email);
}
}
To make a Webservice callout in batch Apex, we have to implement Database.AllowsCallouts interface in the class definition. Here is an example to make webservice callout in batch apex.
Batch Apex:
global class AccountBatchApex implements Database.Batchable<sObject>, Database.AllowsCallouts{
global Database.QueryLocator start(Database.BatchableContext bc){
String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
return Database.getQueryLocator(soqlQuery);
}
global void execute(Database.BatchableContext bc, List<Account> scope){
for (Account acc : scope){
if(acc.Type.equals('Customer - Direct')){
try{
HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
Http http = new Http();
String username = 'YourUsername';
String password = 'YourPassword';
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
request.setHeader('Authorization', authorizationHeader);
request.setHeader('Content-Type', 'application/json');
request.setEndpoint('Your Endpoint URL');
request.setMethod('POST');
request.setBody('Information to Send');
response = http.send(request);
if (response.getStatusCode() == 200) {
String jsonResponse = response.getBody();
System.debug('Response-' + jsonResponse);
}
}
catch(Exception){
System.debug('Error-' + e.getMessage());
}
}
}
}
global void finish(Database.BatchableContext bc){
}
}
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.