Sub topic 1
What an Apex Callout Is and When to Use One
Prerequisites
This chapter assumes you know basic Apex classes and methods, HTTP methods and status codes, JSON, and Salesforce governor limits. You should also be able to create metadata in Setup.
What an Apex Callout Is
An Apex callout is an HTTP request from Salesforce to an external service. Use one when Apex must read data from, send data to, or start an operation in another system.
A callout has two main parts:
- A request describes the method, URL, headers, and optional body.
- A response contains a status code, headers, and body.
A callout can run synchronously from Apex, but the transaction must follow Salesforce rules. For example, a callout after certain database changes can fail with an uncommitted work error. Triggers commonly use asynchronous Apex instead.
The Http, HttpRequest, and HttpResponse Classes
HttpRequest represents the outgoing request. Http sends it. HttpResponse represents the result.
This example requests a todo item through a Named Credential and accepts only a successful response:
public with sharing class TodoService {
public class TodoException extends Exception {}
public static String fetchTodo(Integer todoId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/' + todoId);
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(20000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
return res.getBody();
}
throw new TodoException(
'Unexpected status ' + res.getStatusCode() + ': ' + res.getStatus()
);
}
}The timeout is measured in milliseconds. A failed network operation can raise a CalloutException, so production code should handle that exception at an appropriate boundary.
Authorizing Endpoints: Remote Site Settings
Remote Site Settings authorize a specific external URL for callouts. In Setup, add the service's base URL, such as https://api.example.com.
This authorization does not store an API key or choose an authentication method. It only permits Apex to contact the endpoint. Without authorization, Salesforce blocks the request.
Named Credentials and the `callout:` Prefix
A Named Credential stores an endpoint and authentication configuration as Salesforce metadata. Apex refers to its name instead of embedding a URL or secret.
Use the callout: prefix followed by the Named Credential name:
callout:Todo_API/todos/1
This separates connection configuration from code and makes authentication easier to change safely.
Exercise
Which Apex class sends an HttpRequest, and which class contains the returned status code?
Show answer
Http sends the request, and HttpResponse contains the returned status code.