Sub topic 1
Anatomy of an Apex callout
An Apex callout is an HTTP request that your Apex code sends to a system outside Salesforce. This chapter breaks one callout into its parts and shows where each part can go wrong. Later chapters cover timeouts, error handling, and retries in detail. This one gives you the vocabulary and the working model they build on.
Prerequisites
This chapter assumes you already have the following:
- Basic Apex syntax and classes.
- Familiarity with HTTP methods and status codes.
- Experience writing a simple Apex callout with
Http,HttpRequest, andHttpResponse. - Awareness of Apex governor limits, and of the difference between synchronous and asynchronous Apex.
You do not need to know anything about retries or Queueable yet. If you can read the examples below without looking up the classes, you are ready.
The three classes
Every Apex callout uses three classes from the System namespace:
| Class | Role | Typical members |
|---|---|---|
| `HttpRequest` | Describes what to send | `setEndpoint`, `setMethod`, `setHeader`, `setBody`, `setTimeout` |
| `Http` | Sends the request | `send` |
| `HttpResponse` | Describes what came back | `getStatusCode`, `getStatus`, `getBody`, `getHeader` |
The flow is always the same. You build an HttpRequest, pass it to Http.send, and read the HttpResponse that send returns. Nothing leaves Salesforce until you call send, and send blocks until a response arrives, the timeout expires, or the connection fails.
A complete callout
The class below calls a hypothetical orders API through a Named Credential called Orders_API. It uses every part of the anatomy.
public with sharing class OrderLookup {
public class LookupException extends Exception {}
public static Map<String, Object> getOrder(String orderId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders/' + EncodingUtil.urlEncode(orderId, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(20000); // milliseconds
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new LookupException(
'Orders API returned ' + res.getStatusCode() + ' ' + res.getStatus()
);
}
return (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
}
}This is the happy-path shape. It still has two weaknesses that the rest of the tutorial fixes. Http.send can throw before you ever get a response, and the status check treats every non-200 answer the same way. The sections below explain each part, then return to those weaknesses.
Building the request
The endpoint
setEndpoint takes the full URL of the resource. In production code you should almost always use a Named Credential, written as callout:<Name> followed by a path. A Named Credential stores the base URL and the authentication settings outside your code. It also removes the need for a Remote Site Setting. Without a Named Credential, the host must be allowed in Remote Site Settings, or send fails.
Build the path carefully. The example above runs the orderId through EncodingUtil.urlEncode so that a value containing /, ?, or spaces cannot change the meaning of the URL.
The method
setMethod takes a string such as 'GET', 'POST', 'PUT', 'PATCH', or 'DELETE'. The method matters for later chapters. GET, PUT, and DELETE are defined by HTTP as safe to repeat. POST is not, so retrying a POST needs extra care.
Headers and body
setHeader(name, value) sets one header. setBody(String) sets the payload for methods that carry one. If you send JSON, set Content-Type yourself:
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'sku' => 'A-100',
'quantity' => 2
}));Salesforce does not guess the content type. A missing Content-Type is a common cause of 400 and 415 responses from the other side.
The timeout
setTimeout(Integer) sets how long Apex waits, in milliseconds. The default is 10,000 (10 seconds) and the maximum is 120,000 (120 seconds). Setting the value explicitly, even when it equals the default, documents your intent and protects you if you later change it. A later chapter covers how to choose a value.
Sending and reading the response
new Http().send(req) returns an HttpResponse whenever the remote server answered, whatever the status was. These are the members you will use most:
| Member | Returns |
|---|---|
| `getStatusCode()` | The numeric status, for example `200` or `503` |
| `getStatus()` | The reason phrase, for example `OK` or `Service Unavailable` |
| `getBody()` | The body as a `String` |
| `getBodyAsBlob()` | The body as a `Blob`, for binary content |
| `getHeader(name)` | The value of one response header, or `null` |
| `getHeaderKeys()` | All response header names |
Headers are useful for more than curiosity. A Retry-After header on a 429 or 503 response tells you how long the server wants you to wait, and a later chapter on retry design uses it.
HttpResponse res = new Http().send(req);
String retryAfter = res.getHeader('Retry-After');
if (retryAfter != null) {
System.debug('Server asked us to wait ' + retryAfter + ' seconds');
}Where a callout can fail
A callout has two different failure paths. Mixing them up is the most common mistake in callout code.
- The call throws.
Http.sendraises aSystem.CalloutExceptionwhen no usable HTTP response exists. Causes include a read timeout, a refused connection, a DNS failure, a TLS error, or an endpoint that is not allowed. You never receive anHttpResponsein this case. - The call returns an error response. The server answered, but with a
4xxor5xxstatus.Http.senddoes not throw. You get a normalHttpResponseand must inspectgetStatusCode()yourself.
The OrderLookup example above handles the second path with its status check, and ignores the first. A caller that sees a raw CalloutException learns nothing about which operation failed. A better version wraps it, as in this client:
public with sharing class OrderApiClient {
public class ApiException extends Exception {}
public static HttpResponse send(String path) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API' + path);
req.setMethod('GET');
req.setTimeout(30000); // milliseconds; the default is 10000
try {
return new Http().send(req);
} catch (System.CalloutException e) {
// Thrown for timeouts and connection failures
throw new ApiException('Callout failed: ' + e.getMessage(), e);
}
}
}Passing e as the second argument keeps the original exception as the cause, so the stack trace is not lost. The chapters on failure modes and status handling take this further.
Limits that apply to every callout
You do not need the details yet, but three limits shape how you design a callout from the start. The values below are the documented per-transaction limits.
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Cumulative callout time per transaction | 120 seconds |
| Default timeout per callout | 10 seconds (maximum 120 seconds) |
| Maximum request or response size | 6 MB synchronous, 12 MB asynchronous |
Two consequences follow. First, the 120-second cumulative limit applies to the whole transaction, so a few slow calls with long timeouts can exhaust it even though each call is individually allowed. Second, retrying inside one transaction spends from the same budget, which is the main reason retries in this tutorial run asynchronously.
Where you are allowed to call out
Callouts are restricted by transaction state, not only by limits.
- Uncommitted work. If you perform DML and then make a callout in the same transaction, Salesforce throws a
CalloutExceptionwith the message "You have uncommitted work pending. Please commit or rollback before calling out." The usual fix is to make the callout first, or to move it into a separate asynchronous transaction. - Triggers. A callout cannot run synchronously from a trigger. A trigger must hand the work to asynchronous Apex.
- Asynchronous Apex. A
Queueableclass must implementDatabase.AllowsCalloutsto make callouts. A@futuremethod needs@future(callout=true). - Tests. Test methods cannot make real callouts. Without a registered mock, a callout in a test fails. You register one with
Test.setMock, which is covered in the final chapter.
The following sketch shows the asynchronous pattern in its smallest form:
public class OrderPush implements Queueable, Database.AllowsCallouts {
private final String payload;
public OrderPush(String payload) {
this.payload = payload;
}
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(payload);
req.setTimeout(30000);
HttpResponse res = new Http().send(req);
System.debug('Status: ' + res.getStatusCode());
}
}A trigger or service class starts it with System.enqueueJob(new OrderPush(json));. The job runs in its own transaction after the current one commits, which sidesteps the uncommitted-work error.
A checklist for any callout
Before you write retry logic, check that the basic callout is sound:
- The endpoint uses a Named Credential, and path values are URL-encoded.
- The method and the
Content-Typeheader match what the API expects. - The timeout is set explicitly, in milliseconds.
CalloutExceptionis caught and wrapped where you can add context.- The status code is checked, and the body is parsed only after a success status.
- The callout runs where it is allowed: no pending DML, no synchronous trigger context.
Exercises
Exercise
A callout returns HTTP 503 from the remote service. Does Http.send throw an exception? What must your code do to notice the failure?
Show answer
No. Http.send returns a normal HttpResponse for any status the server sends, including 4xx and 5xx. The code must call getStatusCode() and compare it with the success range (200 to 299). Only timeouts and connection-level failures raise a CalloutException.
Exercise
An Apex method inserts an Account and then calls new Http().send(req) in the same transaction. What happens, and how can you avoid it?
Show answer
Salesforce throws a CalloutException with the message "You have uncommitted work pending". You can avoid it by making the callout before the DML, or by moving the callout into a separate asynchronous job such as a Queueable class that implements Database.AllowsCallouts.