Sub topic 5
Making callouts with Database.AllowsCallouts
This chapter assumes you can write and enqueue a basic Queueable class, and that you know Apex governor limits and the Http classes. It covers how to let a queueable call an external service, and what to watch for.
Why callouts need a marker interface
A callout is an HTTP request from Apex to an external system. Some contexts block callouts. A trigger can't make one synchronously, because the transaction would stay open while it waits for a remote server. Queueable jobs are the usual workaround, since they run in their own transaction after the original one commits.
A queueable doesn't get this ability automatically. The class must also implement the Database.AllowsCallouts marker interface. A marker interface has no methods. It only tells the platform that the class is allowed to make callouts.
A queueable that calls a service
This job fetches a value from an external service and writes it to an account. The endpoint uses a named credential called Ratings_Service. Named credentials keep the URL and authentication out of your code.
public class RatingSyncJob implements Queueable, Database.AllowsCallouts {
private Id accountId;
public RatingSyncJob(Id accountId) {
this.accountId = accountId;
}
public void execute(QueueableContext context) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Ratings_Service/ratings/' + accountId);
req.setMethod('GET');
req.setTimeout(20000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Ratings service returned ' + res.getStatusCode());
}
Account a = new Account(Id = accountId, Description = res.getBody());
update a;
}
}Both interfaces appear in one implements list. You enqueue the job as usual with System.enqueueJob(new RatingSyncJob(acct.Id)).
Do the callout before the DML
The code above makes the callout first and updates the record second. The order matters. If a transaction has performed DML that isn't committed yet, a later callout throws a CalloutException that mentions uncommitted work pending. So in one execute method, make all your callouts first and run your DML afterward.
If you need to alternate between callouts and DML, split the work across chained jobs. Each job runs in a separate transaction, so each one starts with no uncommitted work.
Limits that still apply
Moving to a queueable gives you a fresh transaction, but callout limits still apply inside it:
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Timeout per callout | 10 seconds by default, up to 120 seconds with `setTimeout` |
| Cumulative timeout for all callouts | 120 seconds |
A slow service eats into the cumulative budget, so a loop of 100 slow requests fails long before it reaches 100. Keep the number of callouts per job small and chain a new job for the rest.
Testing callouts
Test methods can't make real HTTP requests. You supply a fake response with Test.setMock and a class that implements HttpCalloutMock. Without the mock, the test fails when the job runs.
@IsTest
private class RatingSyncJobTest {
private class RatingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('Hot');
return res;
}
}
@IsTest
static void storesServiceResponse() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.setMock(HttpCalloutMock.class, new RatingMock());
Test.startTest();
System.enqueueJob(new RatingSyncJob(a.Id));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
System.assertEquals('Hot', result.Description);
}
}The test inserts the account before Test.startTest(). The callout happens later, inside the job, which runs when Test.stopTest() is called.
Exercise
A queueable class implements only Queueable. Its execute method updates an Account and then calls an external service. Name two changes that make it work.
Show answer
Add Database.AllowsCallouts to the implements list, so the platform permits the callout. Then move the callout before the update, because a callout after uncommitted DML throws a CalloutException. In a test, also call Test.setMock with an HttpCalloutMock.