Sub topic 6
Making Callouts with callout=true
This chapter covers how to make HTTP callouts from a future method. It assumes you know basic Apex syntax, SOQL and DML, and how triggers run. It also assumes you know that Salesforce enforces governor limits. You should have read the earlier chapters on declaring future methods and on passing record IDs and re-querying data.
Why callouts need a future method
A callout is a request from Apex to an external system, usually over HTTP. Examples are a REST call to a billing service or a SOAP call to a web service.
Callouts are slow compared with database work. The external server sets the response time, not Salesforce. Salesforce therefore applies two rules that matter here:
- A callout cannot be made after uncommitted DML in the same transaction. Doing so throws a
System.CalloutExceptionwith the message "You have uncommitted work pending. Please commit or rollback before calling out." - Triggers cannot make synchronous callouts. A trigger runs in the middle of a save operation, and the database holds locks until it finishes. Waiting on an external server would hold those locks open.
A future method solves both problems. It runs in its own transaction, after the original transaction commits. No uncommitted work is pending, and no save operation is waiting on the response.
The callout=true attribute
By default, a future method is not allowed to make callouts. To allow them, set the callout attribute:
@future(callout=true)
public static void sendAccounts(Set<Id> accountIds) {
// callouts allowed here
}If you leave the attribute off and try to call out, the platform throws a System.CalloutException at run time. The compiler does not catch this. The error appears only when execution reaches the callout.
The default of callout=false exists so that Salesforce can tell, before running the method, which future methods need the callout path. Always set callout=true when the method contains any callout, including indirect ones. If the method calls a helper class that makes a callout, the attribute is still required.
A complete callout example
The following class reads accounts, serializes them, and posts them to an external endpoint.
public class BillingCallout {
@future(callout=true)
public static void sendAccounts(Set<Id> accountIds) {
List<Account> accounts = [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(accounts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + res.getStatus());
}
}
}Walk through the parts:
- The method is
staticand returnsvoid, as every future method must. - It receives a
Set<Id>, not a list ofAccountrecords. The method re-queries the accounts, so it works with current field values and not a stale copy. callout:Billing_API/accountsuses a Named Credential. Billing_API is a placeholder. You must define a Named Credential with that name in Setup, or the call fails.JSON.serialize(accounts)turns the list into a JSON string for the body.- The method checks the status code and logs a failure.
Why a Named Credential
A Named Credential stores the endpoint URL and the authentication details in one place. It has two benefits for this chapter:
- You do not need to add the URL to Remote Site Settings. The
callout:prefix covers that. - You keep secrets out of code. The platform adds the authentication headers for you.
If you call a raw URL such as https://api.example.com/accounts, you must register that URL in Remote Site Settings first. Without it, the callout fails with an "Unauthorized endpoint" error.
Calling the method
You call the method like any other static method. The platform queues it and returns control immediately.
Set<Id> ids = new Map<Id, Account>([SELECT Id FROM Account LIMIT 10]).keySet();
BillingCallout.sendAccounts(ids);
System.debug('This line runs before the callout happens.');The debug line runs first. The callout happens later, in a separate transaction. This has a consequence you must plan for: the calling code never sees the response. A future method returns void, so it cannot hand the HttpResponse back. If the result matters, the future method must store it, for example by updating a field on the record, creating a log record, or publishing a platform event.
The sequence of events
The diagram shows how the original transaction and the future transaction relate.
Notice that the user gets a response at the "Commit and return" step. The callout has not happened yet at that point.
Handling the response
Because nobody is waiting for the result, error handling is your job. A failed callout does not surface to the user who triggered it. Check the response and record the outcome.
public class BillingCallout {
@future(callout=true)
public static void sendAccounts(Set<Id> accountIds) {
List<Account> accounts = [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.setTimeout(30000);
req.setBody(JSON.serialize(accounts));
try {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR,
'Billing callout failed: ' + res.getStatusCode() + ' ' + res.getStatus());
}
} catch (CalloutException e) {
System.debug(LoggingLevel.ERROR, 'Billing callout error: ' + e.getMessage());
}
}
}Two details are worth noting:
setTimeout(30000)sets the timeout in milliseconds. The default is 10 seconds and the maximum is 120 seconds.- The
try/catchhandlesCalloutException, which covers timeouts, unreachable hosts, and missing Remote Site Settings.
A future method has no built-in retry. If the callout fails, the platform does not run it again. If you need retries, you must build them, and that is one reason to consider Queueable Apex, covered in a later chapter.
Limits that apply to callouts
Callouts in a future method are subject to the governor limits for asynchronous Apex. The values below are the ones to remember. Check the current Apex Developer Guide for exact figures, because Salesforce can change them.
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Maximum timeout per callout | 120 seconds |
| Cumulative timeout for all callouts in one transaction | 120 seconds |
| Maximum request or response size (asynchronous) | 12 MB |
| Future method calls per Apex invocation | 50 |
The cumulative timeout is the one people miss. If you make several slow callouts in a loop, their combined waiting time must stay under 120 seconds, even when each one is within its own limit.
Common errors
| Error | Cause | Fix |
|---|---|---|
| "Callout from triggers are currently not supported" | A callout was made directly in a trigger | Move the callout into a `@future(callout=true)` method |
| "You have uncommitted work pending" | DML ran before the callout in the same transaction | Make the callout in a future method, or do it before any DML |
| "Unauthorized endpoint" | The URL is not in Remote Site Settings and is not a Named Credential | Add the site or use a Named Credential |
| `CalloutException` with no obvious cause inside a future method | The method is missing `callout=true` | Add `callout=true` to the annotation |
| Callout works in a sandbox test but not in a unit test | Unit tests cannot make real callouts | Use `HttpCalloutMock` |
Callouts and DML inside the same future method
The "uncommitted work" rule still applies inside the future method. If your future method updates a record and then makes a callout, the callout fails. Order the work so that the callout comes first and the DML comes afterward:
public class BillingSync {
@future(callout=true)
public static void syncAndMark(Set<Id> accountIds) {
List<Account> accounts = [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(accounts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
for (Account a : accounts) {
a.Description = 'Synced to billing';
}
update accounts;
}
}
}The callout runs first, then the update saves the result. Reversing the order would throw the uncommitted work error.
Testing a callout method
Test methods cannot send real HTTP requests. If a test reaches a callout without a mock, it fails. You supply a mock by implementing HttpCalloutMock and registering it with Test.setMock.
@isTest
private class BillingCalloutTest {
private class SuccessMock implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
res.setBody('{"result":"ok"}');
return res;
}
}
@isTest
static void sendAccountsCallsOut() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.setMock(HttpCalloutMock.class, new SuccessMock());
Test.startTest();
BillingCallout.sendAccounts(new Set<Id>{ a.Id });
Test.stopTest();
System.assertEquals(1, Limits.getFutureCalls());
}
}Two points matter here. First, Test.setMock must run before the callout executes. Second, the future method does not run until Test.stopTest(), so any assertion on its effects must come after that call. The assertion above checks Limits.getFutureCalls(), which counts the future calls queued in the test context. A later chapter covers testing in more detail.
Design guidance
Keep these rules in mind when you write callout future methods:
- Pass IDs, not records, and re-query inside the method.
- Keep the method small. Do the callout, check the result, and record the outcome.
- Record failures somewhere a person can find them, such as a custom log object.
- Do not assume order. Two future methods queued back to back may run in either order, so do not make one depend on the other.
- Do not rely on a callout finishing quickly. If the response is large or the service is slow, consider Queueable Apex, which supports chaining and richer inputs.
Exercise
A trigger on Account calls a normal static method that posts account data to an external API. Saving an account throws "Callout from triggers are currently not supported." Describe the fix, and name two things the fixed method must have.
Show answer
Make the method a future method that makes the callout, and call it from the trigger. It must be annotated @future(callout=true), and it must be static and return void. It should accept a Set<Id> instead of records, then re-query the accounts inside the method. Setting callout=true is required, or the callout fails with a CalloutException at run time.
Exercise
Inside a future method with callout=true, you update an Account and then call an external API. The callout fails with "You have uncommitted work pending." How do you fix it, and why does the error occur?
Show answer
Move the callout before the DML statement. The platform does not allow a callout while uncommitted DML is pending in the same transaction, even inside a future method. Doing the callout first, then updating the record with the result, avoids the error.
Exercise
Your test for a callout future method fails with "Methods defined as TestMethod do not support Web service callouts." What is missing, and where must it go?
Show answer
The test needs a mock. Implement HttpCalloutMock, then call Test.setMock(HttpCalloutMock.class, new YourMock()) before the future method runs. Put the call before or inside the Test.startTest() block, and call Test.stopTest() so the future method executes.