Sub topic 6
Making Callouts with callout=true
This chapter assumes you can write Apex classes and static methods, you know SOQL and DML basics, and you know why a future method must be static, return void, and take only primitive parameters. It covers how a future method makes an HTTP callout to an external service.
Why callouts need a future method
A callout is a request from Apex to an external system, usually over HTTP. Apex does not allow a callout in a trigger. It also blocks a callout in any transaction that has uncommitted DML work pending. The platform holds database locks during a transaction, and a slow external service would hold them open.
A future method runs in its own transaction after the original one commits. That makes it a natural place to put the callout.
Declaring the annotation
A plain @future method cannot make callouts. You must opt in with callout=true.
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());
}
}
}The method follows the same rules as any future method. It takes a set of IDs and re-queries the records, so it works with current data and not a stale snapshot.
The endpoint callout:Billing_API/accounts uses a Named Credential. Billing_API is a placeholder, so you must define a Named Credential with that name in Setup before this code can run. Named Credentials store the base URL and the authentication details outside your code. They also cover the remote site registration that a raw URL would need.
How the flow works
The caller never waits for the response. The user's save finishes first, and the callout happens later.
What you cannot do
Because the future method runs apart from the caller, a few things follow:
- You cannot return the response to the caller. The method returns void.
- You cannot rely on a fixed start time. The platform runs it when resources are free.
- You must handle failure inside the method. An uncaught exception ends the job, and nothing retries it.
If you need the result, write it to a record. For example, update a status field on the account after the response arrives. Do that DML after the callout, not before it.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `Callout from triggers are currently not supported` | The trigger called the external service directly | Move the callout into a `@future(callout=true)` method |
| `You have uncommitted work pending` | DML ran before the callout in the same transaction | Do the callout first, then the DML |
| `Methods defined as TestMethod do not support Web service callouts` | A test reached a real callout | Use `Test.setMock` with an `HttpCalloutMock` |
| `Unauthorized endpoint` | The URL has no Named Credential or remote site entry | Add a Named Credential or Remote Site Setting |
The third error matters most for the next chapters. Tests never make real callouts, so any test that reaches this method must supply a mock response.
@isTest
private class BillingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"ok":true}');
return res;
}
}In a test, call Test.setMock(HttpCalloutMock.class, new BillingMock()); before Test.startTest().
Limits to remember
The future method has its own set of governor limits. A single transaction can make up to 100 callouts, and each callout has a timeout that you can set up to 120 seconds with req.setTimeout(). The total callout time in one transaction cannot exceed 120 seconds.
Exercise
A trigger on Account inserts a related record and then needs to notify an external system. Why does a direct callout in the trigger fail, and what is the fix?
Show answer
Apex does not allow callouts from triggers, and uncommitted DML in the same transaction also blocks them. The fix is to pass the account IDs to a static @future(callout=true) method. It runs in a new transaction after the trigger commits, and it re-queries the records before making the HTTP request.