Sub topic 7
Calling out with Queueable Apex
This chapter assumes you can write a basic Apex trigger and class, know the main governor limits, and understand HTTP requests and JSON. It also assumes you know why a trigger cannot call out directly. A callout inside the trigger's transaction would hold the database open, so Apex blocks it. The fix is to hand the work to asynchronous Apex.
The working model
A Queueable is a class that implements the Queueable interface. When you call System.enqueueJob, Salesforce saves the job and returns right away. The job runs later in its own transaction. That transaction is allowed to make callouts only if the class also implements Database.AllowsCallouts.
The trigger commits first. The Queueable then runs after the commit, so the callout never overlaps the original database work.
The trigger
The trigger does no callout. It enqueues one job for the whole batch of records and passes only their Ids.
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}Because the call sits outside any loop, a bulk insert of 200 accounts enqueues one job, not 200.
The Queueable class
The job re-queries the accounts by Id and sends them in a single bulk request. It uses the Named Credential Billing_API, so the endpoint and authentication stay out of the code.
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public AccountSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new AccountSyncFinalizer());
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Account a : accounts) {
payload.add(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name });
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Sync failed: ' + res.getStatusCode() + ' ' + res.getBody());
}
}
}Points to notice:
Database.AllowsCalloutsis what permits the callout. Without it,sendthrows aSystem.CalloutException.- The constructor stores a
Set<Id>, not records. By the time the job runs, the records may have changed, so the job reads fresh data. - The status code check matters because
senddoes not throw on a 404 or 500. It returns the response, and your code must inspect it. System.attachFinalizerregisters cleanup logic that runs even if the job fails. The next chapters cover it in more detail.
The Finalizer
A Finalizer runs after the Queueable finishes, including when it ends with an unhandled exception.
public class AccountSyncFinalizer implements Finalizer {
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR, 'Queueable failed: ' + ctx.getException().getMessage());
}
}
}Common errors
| Symptom | Likely cause |
|---|---|
| `Callout from triggers are currently not supported` | The callout is still running in the trigger's own transaction. Move it into the Queueable's `execute`. |
| `You have uncommitted work pending` | A callout ran after DML in the same transaction. Keep the callout in the job and do DML afterward. |
| Job never makes the callout | The class does not implement `Database.AllowsCallouts`. |
| Too many queueable jobs | `System.enqueueJob` is inside a loop. Enqueue once per transaction. |
Exercise
Why does the Queueable constructor take a Set<Id> instead of a List<Account>, and what does execute do with it?
Show answer
The records can change between the trigger and the moment the job runs, so a stored copy would be stale. The job takes the Ids, re-queries the accounts in execute, and builds the payload from the current data.
Exercise
A Queueable class implements only Queueable and calls Http.send. What happens, and how do you fix it?
Show answer
The send call throws a System.CalloutException because the class is not allowed to make callouts. Add Database.AllowsCallouts to the class declaration.