Sub topic 1
Anatomy of an Apex Callout
Prerequisites
Assume you know basic Apex classes, HTTP methods and status codes, and the Http, HttpRequest, and HttpResponse classes. You should also understand that Salesforce governor limits restrict work within one transaction.
An Apex callout sends an HTTP request from Salesforce to an external service. HttpRequest describes the request, Http sends it, and HttpResponse contains the result.
public with sharing class OrderApiClient {
public static HttpResponse getOrders() {
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Orders_API/orders');
request.setMethod('GET');
request.setTimeout(30000);
return new Http().send(request);
}
}A named credential, such as Orders_API, stores the endpoint and authentication settings. This keeps secrets out of Apex code.
Callout limits you must plan around
A transaction can make at most 100 callouts. The total timeout for all callouts in one transaction is limited to 120 seconds. These limits include callouts made by code you invoke indirectly, so shared services and loops need special care.
For longer work, use asynchronous Apex such as Queueable Apex. Asynchronous execution still has limits, but it moves the work into a separate transaction.
| Constraint | Planning consequence |
|---|---|
| 100 callouts per transaction | Batch or combine requests instead of calling inside an uncontrolled loop |
| 120 seconds cumulative timeout | Use realistic timeouts and avoid many slow requests |
| One transaction boundary | Move retries into separate asynchronous jobs |
Setting and reasoning about timeouts
setTimeout uses milliseconds. The default is 10,000 milliseconds, or 10 seconds. Set a value that matches the service's normal response time, but do not wait indefinitely. The maximum timeout for one callout is 120 seconds.
request.setTimeout(30000); // 30 secondsA timeout usually throws System.CalloutException. It does not produce a normal HTTP response because Salesforce did not receive one.
Two kinds of failure: exceptions and error responses
A connection failure or timeout throws an exception. By contrast, an HTTP 4xx or 5xx response is still a successful transport operation. Http.send returns an HttpResponse, so your code must inspect its status code.
HttpResponse response = new Http().send(request);
Integer status = response.getStatusCode();
if (status >= 200 && status < 300) {
// Process the response body.
} else {
// Classify the error before deciding whether to retry.
System.debug(LoggingLevel.ERROR, response.getBody());
}Exercise
What does Apex return for an HTTP 404 response, and what happens for a connection timeout?
Show answer
A 404 returns an HttpResponse that your code must inspect. A connection timeout normally throws System.CalloutException.