Sub topic 1
What an Apex Callout Is and When to Use One
An Apex callout is an HTTP request that your Apex code sends to a service outside Salesforce, followed by the response that service returns. This chapter explains what a callout is, why the platform restricts callouts, when a callout is the right tool, and what to check before you write one. Later chapters cover the classes, authorization, limits and testing in detail.
Prerequisites
This chapter assumes you already have the following:
- Basic Apex syntax: classes, methods, collections and exceptions.
- Familiarity with HTTP methods (GET, POST, PUT, PATCH, DELETE), status codes and headers.
- A basic understanding of JSON.
- Awareness of Salesforce governor limits, which are the per-transaction caps the platform enforces on shared resources.
- Permission to create metadata in Setup, for example Named Credentials.
What a callout is
Salesforce runs your Apex on a multitenant platform, where many customers share the same servers. Code on that platform normally works with data inside your org. A callout is the way Apex reaches beyond it. Your code builds an HTTP request, sends it to a URL, waits, and then reads the response.
A callout is outbound. Salesforce is the client and the external system is the server. The opposite direction, where an external system calls into Salesforce, is an inbound integration. That uses the REST or SOAP APIs, or an Apex REST class you expose. This tutorial covers only outbound calls.
Typical uses:
- Fetching data that does not live in Salesforce, such as exchange rates, shipping status or address validation.
- Pushing changes to another system, such as sending a closed-won opportunity to an ERP.
- Triggering work in a service you do not control, such as sending a message or starting a payment.
- Calling another Salesforce org through its REST API.
Apex supports two kinds of callouts:
| Kind | What it is | Main classes |
|---|---|---|
| HTTP (REST-style) | Sends an HTTP request and reads an HTTP response. Usually JSON or XML. | `Http`, `HttpRequest`, `HttpResponse` |
| SOAP web service | Calls a SOAP service using Apex generated from its WSDL (the service's machine-readable description). | Classes generated by the WSDL2Apex tool |
This tutorial focuses on HTTP callouts.
The shape of a callout
Every callout follows the same four steps:
- Authorize the endpoint, so the platform allows your org to contact it.
- Build an
HttpRequestwith an endpoint, method, headers, body and timeout. - Send it with
Http.send(), which blocks until a response arrives or the timeout passes. - Read the
HttpResponse: status code, headers and body.
The key point is that Apex does not open a network connection by itself. The platform sits between your code and the internet. It checks that the endpoint is allowed, enforces the limits and makes the call for you.
A first look at the code
The following class makes a GET callout and checks the status before it uses the body. It calls an endpoint through a Named Credential called Todo_API. A later chapter shows how to set that up. For now, notice the four steps.
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());
}
}This code does four things:
- The
callout:Todo_APIprefix points at a Named Credential, which holds the base URL and authentication settings. setTimeout(20000)sets the wait limit in milliseconds, so this call waits at most 20 seconds.send()is synchronous. The next line does not run until the response arrives or the call fails.- The status code is checked before the body is used. A server can answer with a 404 or 500 and
send()still returns normally.
Why the platform requires authorization
Salesforce does not let Apex call any URL it likes. Every endpoint must be authorized first. There are three reasons.
- Data protection. Without this rule, a developer, or an attacker who gets code into the org, could send customer data to any server on the internet. A list of approved endpoints gives administrators control over where data can go.
- Visibility. Admins can review which outside systems the org talks to.
- Safe secrets. Credentials should not be pasted into code, where they end up in version control and logs.
You authorize an endpoint in one of two ways:
- Remote Site Settings. A list of allowed base URLs. It permits the connection but stores no credentials. Your code must supply authentication itself.
- Named Credentials. A saved definition of an endpoint and how to authenticate to it. Using one both authorizes the endpoint and keeps secrets out of code. This is the preferred approach.
If you call an endpoint that is not authorized, Apex throws a System.CalloutException with a message such as Unauthorized endpoint, please check Setup->Security->Remote site settings. This is the most common first error. The next chapters cover both mechanisms.
When to use a callout
A callout is not the only integration option. Choose it when your Apex code must decide, at runtime, to contact another system and use the result. Compare it with the alternatives:
| Need | Better fit | Why |
|---|---|---|
| Show external records in Salesforce without copying them | External Objects (Salesforce Connect) | No code. Data stays in the other system. |
| Run a scheduled bulk sync of large data sets | An integration tool or the Bulk API from outside | Callouts are limited per transaction. |
| React to a record change and notify another system | Callout from asynchronous Apex, or Platform Events and Change Data Capture | Keeps the user's save fast and reliable. |
| Call a simple HTTP service from a Flow | External Services or an invocable Apex action | Lets admins build the logic without code. |
| Compute a value from an external service inside a custom button or LWC | Apex callout | You control the request and response handling. |
A callout fits well when:
- You need a specific response now to continue your logic, such as validating an address before saving.
- You need full control over headers, body and error handling.
- The request volume is small enough to fit the per-transaction limits.
A callout fits poorly when:
- You need to move thousands of records at once.
- The external service is slow or unreliable and a user is waiting on the page.
- A declarative tool can do the job without code.
Constraints that shape your design
Even at this stage, you should know the main constraints. Later chapters cover each in depth.
- Limits per transaction. A transaction can make a limited number of callouts, and each call has a timeout. The total callout time is also capped.
- Uncommitted work. If your transaction has made DML (inserts, updates or deletes) that is not yet committed, a callout throws an error:
You have uncommitted work pending. Please commit or rollback before calling out.Do the callout first, or move it to asynchronous code. - Triggers cannot call out directly. A trigger runs in a context where DML is in progress, so it must hand the callout to asynchronous Apex such as a Queueable job.
- Tests cannot call out. Test methods are not allowed to make real HTTP calls. You supply a mock response with
HttpCalloutMock.
The following diagram summarizes how to decide where a callout can run.
Common mistakes at this stage
- Skipping authorization. Writing the code first and getting the unauthorized endpoint error at the first run. Set up the Named Credential or Remote Site Setting before you test.
- Assuming
send()throws on HTTP errors. It does not. A 404 or 500 comes back as a normalHttpResponse. It throws aCalloutExceptiononly for failures such as a timeout, a connection failure or an unauthorized endpoint. - Calling out from a trigger. This fails or hits the uncommitted work rule. Use a Queueable job.
- Treating a callout as free. Each call adds latency you do not control. Keep the number of calls per transaction low.
Summary of the model
- A callout is an outbound HTTP request from Apex, made through the platform.
- The endpoint must be authorized, preferably with a Named Credential.
Http.send()is synchronous and returns a response even for HTTP error codes.- Limits and the uncommitted work rule decide where and how you can make the call.
- Choose a callout when Apex must contact another system at runtime and use the result. Choose declarative or asynchronous tools when volume, reliability or ownership point that way.
Exercise
A trigger on Opportunity updates a record and then, in the same transaction, calls a REST service with Http.send(). What happens, and what is the usual fix?
Show answer
The callout fails with a CalloutException saying you have uncommitted work pending, because DML has happened and has not been committed. The usual fix is to move the callout into asynchronous Apex, for example a Queueable class that implements Database.AllowsCallouts, and enqueue it from the trigger handler.
Exercise
Your code calls Http.send() and the remote service replies with status 500. Does send() throw an exception? How should your code find out about the failure?
Show answer
No. send() returns a normal HttpResponse for any status code the server returns. It throws a CalloutException only for problems such as a timeout, a connection failure or an unauthorized endpoint. Your code must check getStatusCode() and handle non-success values itself.
Exercise
Name the two ways to authorize an endpoint for a callout and say which one is preferred and why.
Show answer
The two ways are Remote Site Settings and Named Credentials. Named Credentials are preferred because they authorize the endpoint and also store the base URL and authentication details outside the code. Remote Site Settings only permit the connection, so your code would have to handle credentials itself.