How do you enable and execute external API callouts inside Queueable Apex?
Answer
Basics: Callouts cannot happen in triggers or after uncommitted DML in the same transaction. Queueable Apex gives a clean new transaction where callouts are allowed, so the usual pattern is "trigger enqueues a job, job calls the API."
How it works:
- Class implements
QueueableandDatabase.AllowsCallouts. - Trigger or service enqueues it with
System.enqueueJob. - In
execute(QueueableContext), build anHttpRequestusing a Named Credential (callout:Name/path) so no secrets or remote site settings are needed. - Handle the response, then do DML (callouts must come before DML in the same transaction).
- Optionally enqueue one follow-up job.
Advanced / deep dive: Limits per transaction: 100 callouts, 120 seconds cumulative timeout (a single callout defaults to 10 s and can be set up to 120 s). Async heap is 12 MB, so large responses must be paged. Attach a Finalizer (System.attachFinalizer) to record failures, since an unhandled exception otherwise loses your context. Because you cannot call out after DML in the same transaction, split "do DML" and "call out" across chained jobs. For high volume, a single queueable per record can flood the 24-hour async limit (greater of 250,000 or user licenses x 200); batch multiple records per job.
Code / config example:
public class SyncAccountsJob implements Queueable, Database.AllowsCallouts {
private List<Id> accountIds;
{ .accountIds = ids; }
{
List<Account> accts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
();
req.setEndpoint();
req.setMethod();
req.setHeader(, );
req.setBody(JSON.serialize(accts));
().send(req);
(res.getStatusCode() != ) {
( + res.getStatus());
}
}
}