Sub topic 1
Anatomy of an Apex callout
An Apex callout is an HTTP request that your Salesforce code sends to an external system. Every resilient callout is built from the same three classes and a few configuration choices. This chapter covers those parts. Later chapters add limits, timeouts, error handling, and retries on top of them.
Prerequisites
This chapter assumes you have:
- Basic Apex syntax and classes.
- Familiarity with HTTP methods and status codes.
- Some experience with a simple callout using
Http,HttpRequest, andHttpResponse. - Awareness of governor limits and the difference between synchronous and asynchronous Apex.
The three classes
Three classes in the System namespace do the work:
| Class | Role |
|---|---|
| `HttpRequest` | Describes what to send: endpoint, method, headers, body, timeout. |
| `Http` | Sends a request through its `send` method. |
| `HttpResponse` | Holds what came back: status code, headers, body. |
You build a request, pass it to Http.send, and read the response. The call is synchronous. Your code waits until the remote system answers or the call fails.
A minimal GET
The following class sends a GET request and returns the response body.
public with sharing class OrderApiClient {
public static String 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');
HttpResponse res = new Http().send(req);
System.debug('Status: ' + res.getStatusCode() + ' ' + res.getStatus());
return res.getBody();
}
}Each part of the request matters:
- Endpoint. The
callout:prefix points to a Named Credential calledOrders_API. Salesforce replaces the prefix with the credential's URL and adds authentication for you. - Method.
setMethodtakes a string such asGET,POST,PUT,PATCH, orDELETE. - Headers. Use
setHeaderfor values likeAcceptandContent-Type. - Path values. Encode anything that comes from data, as
urlEncodedoes above, so that it cannot change the shape of the URL.
A POST with a body
For a request with a body, you set the content type and serialize the data yourself.
public with sharing class OrderApiClient {
public static HttpResponse createOrder(Map<String, Object> order) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(order));
return new Http().send(req);
}
}JSON.serialize turns the map into a JSON string, and setBody attaches it. Without the Content-Type header, many APIs reject the body or misread it.
Reading the response
HttpResponse gives you the pieces you need to decide what happened:
getStatusCode()returns the numeric code, such as200or503.getStatus()returns the text, such asOK.getBody()returns the body as a string.getBodyAsBlob()returns it as binary.getHeader('Name')returns one header value, ornullif it is absent.
HttpResponse res = OrderApiClient.createOrder(
new Map<String, Object>{ 'sku' => 'A-100', 'quantity' => 2 });
if (res.getStatusCode() == 201) {
Map<String, Object> created =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
System.debug('Created order ' + created.get('id'));
}Named Credentials and Remote Site Settings
Salesforce blocks callouts to endpoints it has not been told about. A Named Credential is the preferred way to do this. It stores the base URL and the authentication details outside your code, so no secrets appear in Apex. If you pass a raw URL instead, the host must be registered as a Remote Site Setting, and you must manage authentication headers yourself.
Where callouts can run
You can call Http.send from synchronous code such as controllers and services. You can also call it from asynchronous Apex such as Queueable classes that implement Database.AllowsCallouts. Triggers cannot make a callout directly, and a callout is not allowed after uncommitted DML in the same transaction. A later chapter covers both rules and how to work around them.
What `send` can and cannot tell you
A callout can go wrong in two separate ways, and the difference drives everything that follows:
sendthrows aSystem.CalloutException. The request never produced a usable response. Typical causes are a timeout, a connection failure, or a blocked endpoint.sendreturns normally with a 4xx or 5xx status. The remote system answered, and the answer was an error.
Exercise
A teammate wraps new Http().send(req) in a try/catch for CalloutException and logs "Success" after the try block. The API returns 500. What does the log show, and why?
Show answer
It logs "Success". Http.send returns the 500 response normally instead of throwing, so the catch block never runs. The code must read getStatusCode() and check it explicitly.