Sub topic 8
Calling the service from Apex with callout:
This chapter shows how an Apex class reaches an external service through a Named Credential. It assumes you can write basic Apex classes and know HTTP methods, headers and status codes. It also assumes a Named Credential, an External Credential and a permission set already exist, as the earlier chapters set up. Here the focus is the Apex side: the endpoint syntax, what the platform does with it, and the limits that apply.
The endpoint syntax
A callout through a Named Credential uses the callout: scheme in place of a normal URL. The format is:
callout:<Named Credential API name>/<path>?<query string>The part after callout: up to the first / is the API name of the Named Credential. That is the developer name, not the label. Everything after it is appended to the URL stored in the Named Credential.
If the Named Credential Weather_API has the URL https://api.example.com/v1, these endpoints resolve as follows:
| Endpoint in Apex | Request sent to |
|---|---|
| `callout:Weather_API/forecast` | `https://api.example.com/v1/forecast` |
| `callout:Weather_API/forecast?city=Oslo` | `https://api.example.com/v1/forecast?city=Oslo` |
| `callout:Weather_API` | `https://api.example.com/v1` |
Your code never contains the host name or any secret. Changing the service URL, or rotating a key, is a Setup change. You don't redeploy Apex.
A complete GET callout
public with sharing class WeatherService {
public static String getForecast(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Weather_API/forecast?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Weather API returned status ' + res.getStatusCode());
}
return res.getBody();
}
}Three details matter here.
- Encode user-supplied values.
EncodingUtil.urlEncodekeeps a city such asSão PauloorA&Bfrom breaking the query string or injecting extra parameters. The platform does not encode the endpoint for you. - No
Authorizationheader. The External Credential supplies authentication, and any custom header configured on the Named Credential is added too. Setting your ownAuthorizationheader in Apex is usually a sign that the credential setup is incomplete. - Check the status.
sendthrows an exception only when the call cannot complete, for example a timeout or a failed connection. A401or500from the service comes back as a normalHttpResponse, and your code must inspect it.
What happens when you call send
When Http.send runs, the platform does work that your code never sees.
The permission check uses the running user, so two users can run the same class and get different results. A user whose permission sets do not grant the external credential principal fails before any request leaves Salesforce. With a named principal, one shared identity is used toward the external service. With a per user principal, each user's own tokens are used. Either way, the user running the Apex needs the access.
A POST with a body, run asynchronously
Real integrations often send data after a record changes. Callouts are not allowed directly in trigger code, and they cannot follow DML in the same transaction (more on that below). A Queueable class that implements Database.AllowsCallouts is the usual answer.
public with sharing class OrderSyncJob implements Queueable, Database.AllowsCallouts {
private final Id orderId;
private final String orderNumber;
public OrderSyncJob(Id orderId, String orderNumber) {
this.orderId = orderId;
this.orderNumber = orderNumber;
}
public void execute(QueueableContext context) {
Map<String, Object> payload = new Map<String, Object>{
'salesforceId' => String.valueOf(orderId),
'orderNumber' => orderNumber
};
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(payload));
req.setTimeout(30000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() > 299) {
throw new CalloutException(
'Order sync failed with status ' + res.getStatusCode() + ': ' + res.getBody()
);
}
}
}This class assumes a Named Credential with the API name Orders_API. A trigger handler would enqueue it with System.enqueueJob(new OrderSyncJob(o.Id, o.OrderNumber)).
setTimeout takes milliseconds. The default is 10,000 (10 seconds) and the maximum is 120,000 (120 seconds). Raise it only for services that are known to be slow, because waiting time counts toward your transaction's callout time limit.
Choosing the credential at run time
The endpoint is just a string, so you can build it from a variable:
String credentialName = 'Weather_API';
req.setEndpoint('callout:' + credentialName + '/forecast');This is useful when the same code serves several environments or tenants, each with its own Named Credential. Keep the set of possible names small and controlled. Never build the name from raw user input, because a user could then aim your code at any credential they have access to.
If the Named Credential comes from a managed package, include the namespace: callout:ns__Weather_API/forecast.
Limits and restrictions that affect callouts
Using callout: does not remove the normal Apex callout rules.
- Uncommitted work. If your transaction has performed DML and has not committed, a callout fails with "You have uncommitted work pending. Please commit or rollback before calling out." Make the callout first, or move it into a Queueable or
@future(callout=true)method. - Triggers. Callouts run synchronously in a trigger are rejected. Hand the work to asynchronous Apex.
- Count per transaction. A transaction can make at most 100 callouts.
- Total callout time. Combined callout time in a transaction is limited to 120 seconds.
- Size. Response bodies are held in memory, so large responses count against the heap limit.
Common mistakes with the syntax
- Using the label instead of the API name.
callout:Weather API/...fails. Use the API name shown on the Named Credential detail page. - Repeating the base URL. If the Named Credential already ends in
/v1, writingcallout:Weather_API/v1/forecastsends the request to/v1/v1/forecast. - Double or missing slashes. Write exactly one
/between the credential name and the path. - Falling back to a raw URL. An endpoint like
https://api.example.com/v1/forecastbypasses the credential and needs a Remote Site Setting. Otherwise it fails with "Unauthorized endpoint, please check Setup->Security->Remote site settings." It also gives you nowhere safe to keep a secret. - Treating a non-200 response as success. Always check the status code, and decide which codes your code accepts. Some services return
201or204on success.
Exercise
A Named Credential with the API name Billing_API has the URL https://billing.example.com/api. You need to call GET https://billing.example.com/api/invoices?status=open. (1) Write the endpoint string. (2) The code works for you but throws an error before any request is sent when run by a sales user. What is the most likely cause?
Show answer
(1) callout:Billing_API/invoices?status=open. The host and /api come from the Named Credential, so they are not repeated. (2) The sales user probably lacks external credential principal access. Add the external credential principal to a permission set assigned to that user. The credential and the Apex code are fine, because the same code worked for a user who had the access.
Exercise
A trigger on Case updates a related record and then calls callout:Orders_API/cases in the same transaction, and the call fails. Name two reasons it can fail and one fix that addresses both.
Show answer
A callout cannot run synchronously in trigger code, and a callout cannot follow DML that has not been committed ("uncommitted work pending"). Fix both by enqueueing a Queueable class that implements Database.AllowsCallouts and making the callout in its execute method.