Apex Callout Tutorial: Call an External REST API from Apex
To make a REST callout from Apex, create an HttpRequest and set its endpoint, method, headers and timeout. Send it with new Http().send(req), check res.getStatusCode(), and parse res.getBody() into an Apex class with JSON.deserialize. Salesforce blocks the call until the endpoint is authorized, either with a Remote Site Setting or by using a Named Credential (callout:My_Credential/path). Callouts can't run directly inside a trigger, so move them into a Queueable that implements Database.AllowsCallouts or a @future(callout=true) method.
The rest of this tutorial builds that from scratch. It uses a real public API (JSONPlaceholder) so you can paste the code into a Developer Edition org and run it. Then it adds a trigger-safe async job and a test class that covers every branch.
What you'll build
| File | Type | Purpose |
|---|---|---|
JsonPlaceholderService | Apex class | Sends the GET request, handles status codes, parses JSON |
AccountEnrichmentJob | Queueable | Runs the callout asynchronously after an Account insert |
AccountTrigger | Trigger | Enqueues the job (no callout inside the trigger) |
JsonPlaceholderServiceTest | Test class | HttpCalloutMock tests for success, 404, 500, bad JSON, timeout and the trigger path |
For the trigger part, create a Number field on Account called External_User_Id__c (length 18, 0 decimals). The job uses it to look up a user in the external API.
Step 1: Authorize the endpoint
Salesforce refuses any callout to a host it doesn't recognize. Without authorization, Http.send() throws System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings.
You have two ways to authorize a host.
Option A: Remote Site Setting (fine for public, unauthenticated APIs)
- Setup โ Quick Find โ Remote Site Settings โ New Remote Site.
- Remote Site Name:
JsonPlaceholder. - Remote Site URL:
https://jsonplaceholder.typicode.com. - Leave Active checked and save.
This only allows traffic to that host. If the API needs a key or token, you'd have to store and attach it yourself, and that's the job Named Credentials do better.
Option B: Named Credential (use this for any API that needs authentication)
Since Winter '23, Salesforce has used a two-part model. The External Credential holds the authentication (protocol, secrets, principals). The Named Credential holds the URL and points to the External Credential. Salesforce marks legacy named credentials as deprecated, so set up new integrations in the new model.
Here's a typical API-key setup:
- Setup โ Named Credentials โ External Credentials tab โ New. Label
Orders API Auth, Authentication Protocol Custom. - Under Principals, add a Named Principal and give it an authentication parameter, for example
apiKey, with the secret value. - Under Custom Headers on the External Credential, add a header named
x-api-keywith the value{!$Credential.Orders_API_Auth.apiKey}. - Open a permission set, go to External Credential Principal Access, add the principal, and assign the permission set to every user who runs the callout. That includes the user who fires the trigger, because async jobs run as that user.
- Go to the Named Credentials tab โ New. Name it
Orders_API, set URL tohttps://api.example.com, select the External Credential, and enable Allow Formulas in HTTP Header so the header merge field resolves.
In Apex, the endpoint becomes:
req.setEndpoint('callout:Orders_API/v1/orders/' + orderId);
You don't need a Remote Site Setting, and no secret appears in code. One thing that catches people out: Salesforce won't substitute an External Credential secret into the endpoint URL itself. A pattern like ?api_key={!$Credential...} fails with "Illegal character in opaque part". Send the key as a header instead.
| Remote Site Setting | Named Credential | |
|---|---|---|
| Authorizes the host | Yes | Yes |
| Stores secrets/tokens | No | Yes, encrypted |
| Handles OAuth, JWT, Basic auth | No, you write it | Yes, configured in Setup |
| Endpoint change needs a deployment | Yes, if the URL is in code | No, edit the credential |
| Per-user access control | No | Yes, via permission sets |
| Good for | Quick tests, public APIs | Production integrations |
Step 2: Build the request, send it, and parse the response
This service class calls GET /users/{id}. It returns a typed object on 200, returns null on 404, and throws one custom exception for everything else.
public with sharing class JsonPlaceholderService {
public class ServiceException extends Exception {}
// Only declare the fields you need. JSON.deserialize ignores the rest.
public class UserDto {
public Integer id;
public String name;
public String email;
public String phone;
public String website;
}
private static final String BASE_URL = 'https://jsonplaceholder.typicode.com';
private static final Integer TIMEOUT_MS = 20000;
public static UserDto getUser(Integer userId) {
HttpRequest req = new HttpRequest();
req.setEndpoint(BASE_URL + '/users/' + userId);
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(TIMEOUT_MS);
HttpResponse res;
try {
res = new Http().send(req);
} catch (CalloutException e) {
// Timeouts, DNS failures, unauthorized endpoints
throw new ServiceException('Callout failed: ' + e.getMessage());
}
Integer status = res.getStatusCode();
String body = res.getBody() == null ? '' : res.getBody();
if (status == 404) {
return null;
}
if (status < 200 || status > 299) {
throw new ServiceException(
'HTTP ' + status + ' from ' + req.getEndpoint() + ': ' + body.left(500)
);
}
try {
return (UserDto) JSON.deserialize(body, UserDto.class);
} catch (JSONException e) {
throw new ServiceException('Could not parse response: ' + e.getMessage());
}
}
}
Try it in Anonymous Apex (Developer Console โ Debug โ Open Execute Anonymous Window):
System.debug(JsonPlaceholderService.getUser(1));
A few choices in this class are deliberate:
JSON.deserializeinto a typed class. You get compile-time field names and no casting fromMap<String, Object>. If the API sends extra fields,JSON.deserializeskips them.JSON.deserializeStrictthrows instead, which is useful when you want to catch contract changes early.- Arrays. If the endpoint returns a JSON array, deserialize to a list:
(List<UserDto>) JSON.deserialize(body, List<UserDto>.class). - Unknown shapes. For payloads with dynamic keys, use
JSON.deserializeUntyped(body)and cast toMap<String, Object>. - An explicit timeout. The default is 10 seconds. The per-callout maximum is 120,000 ms, and the total timeout across all callouts in one transaction can't go over 120 seconds.
- Truncating the body in error messages. Error bodies can be large HTML pages.
left(500)keeps logs readable.
Sending JSON with POST
The same pattern works for writes. Serialize the payload, set Content-Type, and check for the status code the API actually returns on create (usually 201):
HttpRequest req = new HttpRequest();
req.setEndpoint('https://jsonplaceholder.typicode.com/posts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'title' => 'Renewal reminder',
'body' => 'Contract ends in 30 days',
'userId' => 1
}));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 201) {
throw new JsonPlaceholderService.ServiceException('Create failed: HTTP ' + res.getStatusCode());
}
Map<String, Object> created = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
System.debug('New id: ' + created.get('id'));
If you're building the other direction, where an external system calls into Salesforce, see how to create a REST API in Apex.
Step 3: Handle status codes on purpose
Http.send() does not throw on a 4xx or 5xx response. A 500 comes back as a normal HttpResponse, so if you skip the status check, your code will try to parse an error page as JSON. Decide in advance what each class of status means for your integration:
| Status | Meaning | Sensible handling |
|---|---|---|
| 200, 201, 204 | Success | Parse the body (204 has none) |
| 400 | Your request is malformed | Log the body, fix the payload, don't retry |
| 401, 403 | Auth failed or no permission | Check the Named Credential, principal access, token expiry |
| 404 | Resource doesn't exist | Often a valid business outcome: return null |
| 429 | Rate limited | Retry later from async Apex, respect Retry-After header |
| 500โ599 | Server-side failure | Retry later, alert if it persists |
CalloutException | No HTTP response at all (timeout, DNS, unauthorized endpoint) | Wrap and surface a clear message |
Read response headers with res.getHeader('Retry-After').
Step 4: Make the callout from a trigger (async only)
Calling Http.send() directly from trigger code fails with Callout from triggers are currently not supported. A trigger holds the database transaction open, and Salesforce won't let it wait on an external server. The fix is to hand the work to async Apex.
A related rule applies everywhere: you can't make a callout after uncommitted work in the same transaction. DML, enqueuing async jobs, scheduling Apex or sending email all count as pending work. Once any of them happens, a later callout fails with "You have uncommitted work pending". Callouts made before that work are fine, so the usual pattern is to do all callouts first and all DML last.
The trigger only collects IDs and enqueues the job:
trigger AccountTrigger on Account (after insert) {
List<Id> accountIds = new List<Id>();
for (Account acc : Trigger.new) {
if (acc.External_User_Id__c != null) {
accountIds.add(acc.Id);
}
}
if (!accountIds.isEmpty()) {
System.enqueueJob(new AccountEnrichmentJob(accountIds));
}
}
The Queueable does the callouts first and then one update:
public with sharing class AccountEnrichmentJob implements Queueable, Database.AllowsCallouts {
private final List<Id> accountIds;
public AccountEnrichmentJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> toUpdate = new List<Account>();
// 100 callouts per transaction is the hard cap
for (Account acc : [
SELECT Id, External_User_Id__c
FROM Account
WHERE Id IN :accountIds AND External_User_Id__c != null
LIMIT 100
]) {
try {
JsonPlaceholderService.UserDto user =
JsonPlaceholderService.getUser(acc.External_User_Id__c.intValue());
if (user != null) {
toUpdate.add(new Account(Id = acc.Id, Phone = user.phone, Website = user.website));
}
} catch (JsonPlaceholderService.ServiceException e) {
System.debug(LoggingLevel.ERROR, 'Enrichment failed for ' + acc.Id + ': ' + e.getMessage());
}
}
update toUpdate; // DML after all callouts
}
}
Database.AllowsCallouts is required. Without it, the job fails at the first send(). The trigger handles inserts in bulk, so 200 records from a data load means one job, not 200. Each transaction allows 100 callouts, so if an insert can include more than 100 records that need enrichment, switch to Batch Apex with Database.AllowsCallouts and a small scope size such as 50. If your trigger logic is growing, a handler pattern keeps this enqueue step out of the trigger body. The free Apex Triggers Framework 101 course covers that in 8 short episodes.
| Async option | Callout flag | Accepts sObjects/complex params | Chaining | When to use |
|---|---|---|---|---|
@future(callout=true) | On the annotation | No (primitives and collections of primitives only) | No | Small fire-and-forget calls |
| Queueable | Database.AllowsCallouts | Yes | Yes | Default choice from triggers |
| Batch Apex | Database.AllowsCallouts | Yes | Yes (finish method) | Hundreds or thousands of records |
Step 5: Test it with HttpCalloutMock
Test methods can't make real HTTP calls. If you don't register a mock, the callout fails. Test.setMock(HttpCalloutMock.class, mock) sends every Http.send() in that test to your mock class instead. The class below covers every branch in the service, the Queueable and the trigger.
@IsTest
private class JsonPlaceholderServiceTest {
private static final String USER_JSON =
'{"id":1,"name":"Leanne Graham","email":"Sincere@april.biz",' +
'"phone":"1-770-736-8031 x56442","website":"hildegard.org","extra":"ignored"}';
private class MockResponse implements HttpCalloutMock {
private Integer statusCode;
private String body;
public HttpRequest lastRequest;
MockResponse(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
lastRequest = req;
HttpResponse res = new HttpResponse();
res.setStatusCode(statusCode);
res.setHeader('Content-Type', 'application/json');
res.setBody(body);
return res;
}
}
private class TimeoutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
throw new CalloutException('Read timed out');
}
}
@IsTest
static void returnsUserOn200() {
MockResponse mock = new MockResponse(200, USER_JSON);
Test.setMock(HttpCalloutMock.class, mock);
JsonPlaceholderService.UserDto user = JsonPlaceholderService.getUser(1);
Assert.areEqual('Leanne Graham', user.name);
Assert.areEqual('GET', mock.lastRequest.getMethod());
Assert.isTrue(mock.lastRequest.getEndpoint().endsWith('/users/1'));
}
@IsTest
static void returnsNullOn404() {
Test.setMock(HttpCalloutMock.class, new MockResponse(404, '{}'));
Assert.isNull(JsonPlaceholderService.getUser(999));
}
@IsTest
static void throwsOnServerError() {
Test.setMock(HttpCalloutMock.class, new MockResponse(500, 'Internal Server Error'));
try {
JsonPlaceholderService.getUser(1);
Assert.fail('Expected ServiceException');
} catch (JsonPlaceholderService.ServiceException e) {
Assert.isTrue(e.getMessage().contains('HTTP 500'));
}
}
@IsTest
static void throwsOnMalformedJson() {
Test.setMock(HttpCalloutMock.class, new MockResponse(200, 'not json'));
try {
JsonPlaceholderService.getUser(1);
Assert.fail('Expected ServiceException');
} catch (JsonPlaceholderService.ServiceException e) {
Assert.isTrue(e.getMessage().startsWith('Could not parse'));
}
}
@IsTest
static void wrapsCalloutException() {
Test.setMock(HttpCalloutMock.class, new TimeoutMock());
try {
JsonPlaceholderService.getUser(1);
Assert.fail('Expected ServiceException');
} catch (JsonPlaceholderService.ServiceException e) {
Assert.isTrue(e.getMessage().contains('Read timed out'));
}
}
@IsTest
static void triggerEnqueuesJobThatEnrichesAccount() {
Test.setMock(HttpCalloutMock.class, new MockResponse(200, USER_JSON));
Test.startTest();
insert new Account(Name = 'Acme', External_User_Id__c = 1);
Test.stopTest(); // the Queueable runs here, synchronously
Account acc = [SELECT Phone, Website FROM Account WHERE Name = 'Acme'];
Assert.areEqual('1-770-736-8031 x56442', acc.Phone);
Assert.areEqual('hildegard.org', acc.Website);
}
}
Why it's built this way:
- One mock class with configurable status and body covers every response branch without writing a new class per scenario.
lastRequestlets you assert on the request your code sent: endpoint, method and headers. Wrong endpoints and missing headers are common integration bugs, and coverage alone won't catch them.Test.startTest()/Test.stopTest()around the insert forces the enqueued job to run before your assertions. The insert and the callout end up in separate transactions, so the test doesn't hit the uncommitted-work error.- The
Assertclass (Assert.areEqual,Assert.isNull,Assert.fail) reads more clearly thanSystem.assertEqualsand gives better failure messages.
If you'd rather keep large sample payloads out of code, StaticResourceCalloutMock and MultiStaticResourceCalloutMock serve responses from static resources. For the thinking behind tests that check behavior and don't just chase the 75% deployment threshold, read Apex test classes: beyond 75% code coverage.
Callout limits to design around
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Default timeout per callout | 10 seconds |
| Maximum timeout per callout | 120 seconds (120,000 ms) |
| Total callout time per transaction | 120 seconds |
| Callout after uncommitted DML / async / email | Not allowed in the same transaction |
| Callout directly from a trigger | Not allowed; use async Apex |
Callout wait time doesn't count toward the org's long-running request limit. Salesforce pauses that timer during the callout.
Where Salesforce Casts fits
This tutorial covers one GET, one POST and one async path. Production integrations add OAuth flows, token refresh, JWT bearer auth and higher volumes. The Salesforce Integration Master Course is the largest course in the catalogue. It covers OAuth, connected apps, Named and External Credentials, JWT, REST in Apex, Platform Events and Bulk API 2.0. Teja, an ex-engineer at Salesforce.com, writes the code live in a real org, with no slide decks.
For the test side, Apex Test Fest covers async tests, System.runAs, the Assert class and callout mocks. Every course has a GitHub repo with the source code, and every plan unlocks every course.
FAQ
Why do I get "Callout from triggers are currently not supported"?
Your trigger, or code it calls synchronously, ran Http.send(). Salesforce won't hold a trigger's transaction open while it waits on an external server. Move the callout into a Queueable that implements Database.AllowsCallouts or a @future(callout=true) method, and enqueue it from the trigger.
Do I need a Remote Site Setting if I use a Named Credential?
No. A callout to a callout:Name/... endpoint is authorized by the Named Credential itself. You only need a Remote Site Setting when your code calls a full https:// URL directly.
How do I fix "You have uncommitted work pending"?
Put all callouts in the transaction before any DML, async job enqueue or email send. If that order isn't possible, split the work: commit the DML, then do the callout in a Queueable. In tests, run the code that makes the callout between Test.startTest() and Test.stopTest(), after your setup DML.
How many callouts can one Apex transaction make?
- The total wait across all of them can't exceed 120 seconds. If you have more than 100 records to sync, use Batch Apex with
Database.AllowsCalloutsand a scope size that keeps each batch under the limit.
Can I deploy callout code without a test that mocks the callout?
Not in practice. Test methods can't make real callouts, so any test that reaches Http.send() without Test.setMock fails, and that code stays uncovered. Production deployments need 75% org-wide coverage, and a mock-based test class like the one above gets the callout path close to full coverage.
Should I use JSON.deserialize or JSON.deserializeUntyped?
Use JSON.deserialize with an Apex class when the response shape is known. You get typed fields and cleaner code. Use JSON.deserializeUntyped when keys are dynamic or you only need one or two values from a large payload.
Next step
Paste the four files into a Developer Edition org, create the Remote Site Setting, and run JsonPlaceholderServiceTest to see the coverage. Then swap the endpoint for a Named Credential pointing at an API you actually use. When you're ready for OAuth and JWT, the Integration Master Course is included in every plan on the pricing page.
My web search tool hit its usage limit after one query. That query returned the Salesforce callout-limits documentation and several Named Credentials sources, so I couldn't add inline citations, but I checked the timeout, pending-work and Named Credential details against those sources. Before you publish, confirm these against the current Apex Developer Guide: the 100-callout limit, the trigger error text, and the "Allow Formulas in HTTP Header" option. I also haven't run the code. Deploy it to a Developer Edition org once to make sure it compiles and the tests pass.
I used "Salesforce Casts" instead of "Salesforce Casrs" because your page titles and product facts spell it that way.
Learn it by building it
Every course, every code repository, the discussion group and certificates of completion โ one subscription.