Most Salesforce orgs talk to at least one outside system: an ERP, a payment provider, a shipping service. The Apex code for a single HTTP call is short. The hard part is everything around it: where the credentials live, what happens when the other system is slow, and how you test it. This guide covers the patterns I rely on.
Use Named Credentials for every endpoint
Don't put URLs, usernames, passwords or tokens in Apex. Use a Named Credential instead. It holds the endpoint URL, and the authentication settings live in the External Credential it points to.
You call it with the callout: scheme:
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Order_API/v1/orders');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody()); Why this matters:
- Salesforce handles authentication. Your code doesn't build authorization headers, which is especially helpful with OAuth.
- No Remote Site Setting is needed for the endpoint in the Named Credential.
- The URL can change without a deployment. Update the Named Credential and every callout keeps working.
- The same code works in every org. Sandbox and production can each have a Named Credential with the same name and a different URL. No
if (isSandbox)checks.
Know the limits
These limits come straight from the Apex Developer Guide:
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Default timeout per callout | 10 seconds |
| Maximum timeout per callout | 120 seconds |
| Total callout time per transaction | 120 seconds |
Set a timeout that fits the service. The default 10 seconds is often too short for slow APIs and too long for a user waiting on a screen.
HttpRequest req = new HttpRequest();
req.setTimeout(20000); // milliseconds Callouts and DML don't mix freely
You can't make a callout after DML in the same transaction while that work is still pending. The same goes for pending async jobs, scheduled Apex and sending email. If you try, you get an "uncommitted work pending" error.
You have two clean options:
- Make the callout first, then do your DML.
- Move the callout into async Apex so it runs in its own transaction.
Option 2 is also the right choice for anything started by a trigger, because triggers can't make synchronous callouts.
A service class for the callout
Keep the HTTP code in one class. Everything else calls this class instead of building requests itself.
public with sharing class OrderApiService {
public class OrderApiException extends Exception {}
public static HttpResponse sendOrder(String jsonBody) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Order_API/v1/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(jsonBody);
req.setTimeout(20000);
return new Http().send(req);
}
public static Boolean isRetryable(Integer statusCode) {
// Server errors and rate limits are worth another try.
// 4xx errors (bad data, auth) won't fix themselves.
return statusCode == 429 || statusCode >= 500;
}
} Run callouts async with Queueable
A Queueable class that implements Database.AllowsCallouts can make callouts. It is the pattern I use most, because it accepts complex parameters, returns a job ID you can monitor, and can chain to another job.
Here the job sends an Account to the external system and tries again if the server had a temporary problem.
public with sharing class OrderSyncJob implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 3;
private final Id accountId;
private final Integer attempt;
public OrderSyncJob(Id accountId, Integer attempt) {
this.accountId = accountId;
this.attempt = attempt;
}
public void execute(QueueableContext context) {
Account acc = [
SELECT Id, Name, AccountNumber
FROM Account
WHERE Id = :accountId
WITH USER_MODE
];
String body = JSON.serialize(new Map<String, Object>{
'id' => acc.Id,
'name' => acc.Name,
'accountNumber' => acc.AccountNumber
});
Integer statusCode;
try {
HttpResponse res = OrderApiService.sendOrder(body);
statusCode = res.getStatusCode();
} catch (CalloutException e) {
// Timeouts and connection errors land here
statusCode = 503;
}
if (statusCode >= 200 && statusCode < 300) {
return; // success
}
if (OrderApiService.isRetryable(statusCode)
&& attempt < MAX_ATTEMPTS
&& !Test.isRunningTest()) {
// Wait a little longer before each new attempt (in minutes)
System.enqueueJob(new OrderSyncJob(accountId, attempt + 1), attempt);
} else {
// Out of attempts or a permanent error: record it for follow-up
System.debug(LoggingLevel.ERROR,
'Order sync failed for ' + accountId + ' with status ' + statusCode);
}
}
} Start it with:
System.enqueueJob(new OrderSyncJob(accountId, 1)); A few notes on this design:
- Callout first, DML after. The job queries, calls out, then decides what to do. If you need to save a status on the record, do the update after the callout.
- Only retry what can recover. A 400 means your data is wrong. Retrying won't help. A 503 or a timeout might succeed a minute later.
- The delay grows with each attempt.
System.enqueueJobaccepts a delay in minutes, so the second attempt waits 1 minute and the third waits 2. - Chaining is skipped in tests to keep them simple. Apex can test chained jobs if you configure the stack depth, but the retry path is easier to cover by testing
isRetryabledirectly. The delay is ignored in tests anyway. It can be up to 10 minutes.
💡 Log failures somewhere people look
System.debug is fine for this example, but nobody reads debug logs in production. Write failed syncs to a custom log object, or publish a platform event, so an admin can see and replay them.
Handling many records
If a trigger fires for 200 Accounts, don't enqueue 200 jobs. There is a limit on how many Queueable jobs you can add in one transaction. Pass a set of IDs to one job and send them in batches the API accepts, keeping under 100 callouts per transaction. For very large volumes, use Batch Apex with Database.AllowsCallouts.
Test with HttpCalloutMock
Tests can't make real callouts. Implement HttpCalloutMock to return a fake response, and register it with Test.setMock.
@IsTest
private class OrderApiServiceTest {
private class SuccessMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(201);
res.setHeader('Content-Type', 'application/json');
res.setBody('{"externalId":"EXT-1001"}');
return res;
}
}
@IsTest
static void sendOrderReturnsCreated() {
Test.setMock(HttpCalloutMock.class, new SuccessMock());
Test.startTest();
HttpResponse res = OrderApiService.sendOrder('{"name":"Test"}');
Test.stopTest();
Assert.areEqual(201, res.getStatusCode());
}
@IsTest
static void serverErrorsAreRetryable() {
Assert.isTrue(OrderApiService.isRetryable(503));
Assert.isTrue(OrderApiService.isRetryable(429));
Assert.isFalse(OrderApiService.isRetryable(400));
}
} Write one mock per scenario you care about: success, a 400 with an error body, a 500, and a timeout. The failure paths are where integrations break, so they deserve the most tests.
Checklist
- Every endpoint uses a Named Credential
- Timeouts are set on purpose
- Callouts happen before DML, or in async Apex
- Trigger-started integrations use Queueable, not synchronous callouts
- Only temporary errors are retried, with a limit
- Failures are logged where an admin will see them
- Tests cover success and failure responses with mocks