# How do you enable and execute external API callouts inside Queueable Apex?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Queueable Apex

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Class implements `Queueable` and `Database.AllowsCallouts`.
2. Trigger or service enqueues it with `System.enqueueJob`.
3. In `execute(QueueableContext)`, build an `HttpRequest` using a Named Credential (`callout:Name/path`) so no secrets or remote site settings are needed.
4. Handle the response, then do DML (callouts must come before DML in the same transaction).
5. 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:**
```apex
public class SyncAccountsJob implements Queueable, Database.AllowsCallouts {
    private List<Id> accountIds;
    public SyncAccountsJob(List<Id> ids) { this.accountIds = ids; }

    public void execute(QueueableContext ctx) {
        List<Account> accts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:Billing_API/accounts');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(JSON.serialize(accts));
        HttpResponse res = new Http().send(req); // callout BEFORE any DML
        if (res.getStatusCode() != 200) {
            throw new CalloutException('Billing sync failed: ' + res.getStatus());
        }
    }
}
```

**Hidden gotchas & must-remember points:**
- Forgetting `Database.AllowsCallouts` is the classic error.
- "Uncommitted work pending" occurs if DML precedes a callout in the same transaction.
- Tests need `Test.setMock(HttpCalloutMock.class, ...)`; real callouts are never made in tests.
- Only one child job can be enqueued from inside a running queueable.
- Pass sObjects or primitives into the constructor; instance state is serialized.
- Named Credentials avoid Remote Site Settings and credential storage in code.

**Best practice:** Use Named Credentials, bulk the payload, and add a Finalizer for error logging and bounded retry.

---
Source: ForceChallenges · last updated 2026-11-02
