Sub topic 3
Callout Limits and Asynchronous Apex
Assume you know basic Apex classes, exceptions, HTTP status codes, JSON, and governor limits. An Apex callout is a request from Salesforce to an external HTTP service.
Callout limits and timeouts
A transaction can make at most 100 HTTP callouts. Each request can wait up to 120 seconds, and the total timeout for callouts in one transaction is also limited to 120 seconds. Set a shorter timeout when the service should respond quickly.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/1');
req.setMethod('GET');
req.setTimeout(20000); // 20 seconds
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
System.debug(res.getBody());
}A timeout raises a CalloutException. An HTTP error such as 404 or 500 usually does not raise that exception, so always inspect the response status code.
Uncommitted work and callouts from triggers
Salesforce normally prevents a callout after pending database changes in the same transaction. Otherwise, the transaction could wait on a network service while holding uncommitted work. This produces the “You have uncommitted work pending” error.
Perform the callout before DML, or move it to asynchronous Apex. A trigger should usually enqueue a job rather than call an external service directly.
Running callouts asynchronously
Queueable Apex supports callouts when the class implements Database.AllowsCallouts.
public class TodoSyncJob implements Queueable, Database.AllowsCallouts {
private Integer todoId;
public TodoSyncJob(Integer todoId) {
this.todoId = todoId;
}
public void execute(QueueableContext context) {
TodoService.fetchTodo(todoId);
}
}
// System.enqueueJob(new TodoSyncJob(1));@future(callout=true) is another option, but Queueable Apex supports state, chaining, and better job monitoring.
Testing callouts
Tests cannot make real HTTP requests. Implement HttpCalloutMock, register it with Test.setMock, and assert the returned behavior.
Test.setMock(HttpCalloutMock.class, new TodoClientMock());
Test.startTest();
TodoClient.Todo result = TodoClient.create(input);
Test.stopTest();
System.assertEquals(201, result.id);Continuations for long-running callouts
A Continuation is a Visualforce or Aura mechanism for long-running callouts. It lets the request continue without blocking the user-facing request thread. Use it when the platform and UI framework support it. Queueable Apex is usually the simpler choice for background work.
Exercise
What should a trigger do when it must call an external service after inserting records?
Show answer
Enqueue Queueable Apex that implements Database.AllowsCallouts, then perform the callout in its execute method.