Sub topic 5
Making callouts with Database.AllowsCallouts
This chapter assumes you can write a basic Queueable class, enqueue it with System.enqueueJob, and read an Apex governor limit table. You will learn how to let a queueable call an external service, why the order of DML and callouts matters, and how to test the result.
Why callouts belong in queueables
A callout is an HTTP request (or a SOAP call) from Apex to a system outside Salesforce. Callouts are slow and unpredictable, and Salesforce restricts them in several places. A trigger cannot make a callout directly. A callout also cannot run once the same transaction has performed DML without committing it. A queueable runs in its own transaction after the original one commits, so it is the standard place to move that work.
A queueable does not get callout permission by default. You opt in by implementing a second interface, Database.AllowsCallouts, which is a marker interface. It has no methods, and it only tells the platform that execute may call out.
public class AccountScoreJob implements Queueable, Database.AllowsCallouts {
private List<Id> accountIds;
public AccountScoreJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [
SELECT Id, Name FROM Account WHERE Id IN :accountIds
];
List<Account> toUpdate = new List<Account>();
for (Account a : accounts) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Scoring_API/scores?name='
+ EncodingUtil.urlEncode(a.Name, 'UTF-8'));
req.setMethod('GET');
req.setTimeout(20000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
a.Description = 'Score: ' + body.get('score');
toUpdate.add(a);
} else {
System.debug(LoggingLevel.WARN,
'Scoring failed for ' + a.Id + ': ' + res.getStatusCode());
}
}
update toUpdate;
}
}The endpoint uses the callout: prefix, which refers to a Named Credential. This example assumes your org has a Named Credential called Scoring_API. A Named Credential stores the base URL and the authentication settings, so neither appears in code. If you use a plain URL instead, an admin must add it as a Remote Site Setting. Without either one, the callout fails at runtime.
The class has two properties worth noticing:
- The callout happens inside the loop, and the single
updatecomes after the loop. This order is required, as the next section explains. - Only successful responses are collected for the update, so one bad response does not block the others.
The uncommitted work rule
Salesforce does not allow a callout when the current transaction holds uncommitted DML. If you break this rule, you get a System.CalloutException with the message "You have uncommitted work pending. Please commit or rollback before calling out."
The rule exists because a callout can take a long time. The platform would otherwise have to hold database locks open while it waits for an external server.
The rule applies inside the queueable's own transaction too. This code fails:
public void execute(QueueableContext context) {
insert new Account(Name = 'Audit record'); // DML first
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Scoring_API/ping');
req.setMethod('GET');
new Http().send(req); // CalloutException
}Reverse the order and it works. All callouts come first, and DML comes last:
Enqueuing the next job is not a callout, and it is allowed after DML. A chained job therefore does its callouts, then its DML, then enqueues its successor.
You can use this to your advantage when the original code must do DML and then call out. Do the DML in the original transaction and enqueue the callout job in the same transaction. Salesforce only starts the job after the transaction commits:
public with sharing class AccountService {
public static void createAndScore(List<Account> newAccounts) {
insert newAccounts;
List<Id> ids = new List<Id>(new Map<Id, Account>(newAccounts).keySet());
System.enqueueJob(new AccountScoreJob(ids));
}
}If the original transaction rolls back, the job is never queued, so it cannot process records that do not exist.
Limits that apply to callouts
The queueable's transaction gets its own set of limits, and the callout limits are among them.
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Cumulative callout time per transaction | 120 seconds |
| Default timeout for one callout | 10 seconds |
| Maximum timeout you can set for one callout | 120 seconds |
| Maximum request or response size in asynchronous Apex | 12 MB |
Two of these catch people out:
- The 100-callout cap counts every callout in the transaction. The example job makes one callout per account, so a list of 101 IDs would fail with a limit exception on the 101st call. Either pass a smaller list or process the list in slices, a technique covered in the chunking chapter.
- The 120-second total is shared. Ten callouts that each take 15 seconds use 150 seconds, so the job fails even though each call is under the per-call maximum. Set
setTimeoutdeliberately. A shorter timeout makes the job fail fast and leaves you time to retry.
You can check your position at runtime with Limits.getCallouts() and Limits.getLimitCallouts(). These methods are useful when a loop might approach the cap.
if (Limits.getCallouts() >= Limits.getLimitCallouts()) {
// Stop here and hand the remaining IDs to a new job.
}Each job in a chain is a separate transaction. The counters reset when the next job starts, so a chain can make a large number of callouts in total. It still cannot make more than 100 in any single job.
Handling the response
An external call can fail for reasons you cannot control. These are the checks to make in every callout job:
- Check the status code before parsing. An error page is usually not valid JSON, and
JSON.deserializeUntypedthrows on it. - Distinguish HTTP errors from exceptions. A 500 response returns normally from
send, and you read the code fromHttpResponse. A timeout or DNS failure throws aSystem.CalloutExceptioninstead. - Decide what a failure means. For a transient failure, such as a timeout or a 503, a retry may succeed. For a 400, the same request will fail again.
A try/catch around send handles the second case:
HttpResponse res;
try {
res = new Http().send(req);
} catch (CalloutException e) {
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + e.getMessage());
return;
}Catching the exception means the job ends normally, so a finalizer will see a success result. If you want the finalizer to detect the failure and retry, let the exception escape instead. The finalizer chapters cover this choice.
Testing a callout job
Apex tests cannot make real callouts. A test that reaches Http.send without a mock fails with "Methods defined as TestMethod do not support Web service callouts." You supply a fake response with Test.setMock and a class that implements HttpCalloutMock.
@IsTest
private class AccountScoreJobTest {
private class ScoreMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setHeader('Content-Type', 'application/json');
res.setBody('{"score": 87}');
return res;
}
}
@IsTest
static void storesScoreFromService() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.setMock(HttpCalloutMock.class, new ScoreMock());
Test.startTest();
System.enqueueJob(new AccountScoreJob(new List<Id>{ a.Id }));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
System.assertEquals('Score: 87', result.Description);
}
}The test inserts the account before it enqueues the job, and both happen in the same test transaction. This is allowed because the queueable runs when Test.stopTest is called, in its own transaction, after the earlier DML has been committed. Set the mock before stopTest. The job reads the mock at the moment it runs.
To test the failure path, write a second mock class that returns status 500 and assert that the description stays unchanged.
Common mistakes
- DML before the callout. This is the most common failure. Use the order shown in the diagram.
- Callouts in a loop with no cap. Check
Limits.getCallouts()or slice the input. - Leaving the default 10-second timeout on a slow service. Set the timeout explicitly.
- Missing endpoint configuration. A Named Credential or Remote Site Setting must exist in every org where the job runs, including sandboxes.
- Real callouts in tests. Every test that reaches a callout needs a mock.
Exercise
A queueable that implements Database.AllowsCallouts inserts an audit record and then calls an external API. It throws "You have uncommitted work pending." How do you fix it without removing the audit record?
Show answer
Move the DML after the callout in execute, so the callout runs while the transaction has no uncommitted work. If the audit record must exist before the callout, insert it in the code that enqueues the job. The enqueued queueable starts only after that transaction commits, and its own transaction then begins with no pending DML.
Exercise
A job receives 150 account IDs and makes one callout per account. What happens, and what two changes would prevent it?
Show answer
The job fails with a limit exception on the 101st callout, because one transaction allows at most 100 callouts. You can pass at most 100 IDs per job, or process a slice of the list in each job and enqueue a chained job with the remaining IDs. Checking Limits.getCallouts() against Limits.getLimitCallouts() lets the job stop cleanly before the cap.
Exercise
In a test for a callout queueable, where must Test.setMock be called, and why can you insert the test data before it?
Show answer
Call it before Test.stopTest, because the queueable runs when stopTest is called and reads the mock then. Inserting data first is allowed because the queueable runs in its own transaction after the test's DML, so there is no uncommitted work pending when the callout happens.