Sub topic 2
Calling Out with Asynchronous Apex
Prerequisites: basic Apex classes, bulkified triggers, governor limits, and HTTP requests.
Calling Out with a Future Method
A trigger runs inside a database transaction. A synchronous callout would keep that transaction open while Salesforce waits for another system. Move the callout to asynchronous Apex, which runs after the transaction finishes.
A future method is a static method marked with @future. Use callout=true to allow HTTP requests:
public class AccountCalloutService {
@future(callout=true)
public static void syncAccounts(Set<Id> accountIds) {
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Id IN :accountIds
];
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Billing_API/accounts');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setBody(JSON.serialize(accounts));
HttpResponse response = new Http().send(request);
System.debug('Status: ' + response.getStatusCode());
}
}A future method must be static, return void, and accept only primitive values or collections of primitives. Its execution order is not guaranteed, and one future method cannot enqueue another future method.
Calling Out with Queueable Apex
Queueable Apex is usually a better default for new code. A Queueable class can hold state, has a job ID, and can be extended with chaining or a finalizer.
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public AccountSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Id IN :accountIds
];
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Billing_API/accounts');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setBody(JSON.serialize(accounts));
HttpResponse response = new Http().send(request);
if (response.getStatusCode() < 200 ||
response.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Sync failed');
}
}
}Database.AllowsCallouts gives the Queueable job permission to make callouts.
Passing Ids and Re-querying in Async Code
Pass record IDs, not trigger sObjects. The trigger records are tied to the original transaction and may not represent the committed data when the async job runs. Re-query the records inside execute or the future method.
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}Keeping the Pattern Bulk-Safe
Triggers can receive many records at once. Enqueue one job for the whole trigger batch, and send one request containing all records. Do not enqueue a job or make a callout inside a loop.
A response that updates the same object can fire the trigger again. Use a field, change check, or carefully scoped static guard so the update does not enqueue the same work repeatedly.
Exercise
What should a trigger pass to a Queueable callout job?
Show answer
Pass a collection of record IDs. The job should re-query the records and process the whole collection in one bulk operation.