Sub topic 8
Calling the service from Apex with callout:
This chapter assumes you can write basic Apex classes, know HTTP methods, headers and status codes, and can navigate Setup. It also assumes the Named Credential Weather_API, its External Credential Weather_EC and the permission set Weather_Callout_Access already exist, as outlined in the earlier chapters.
What the callout: prefix does
In Apex, an endpoint normally holds a full URL. With a Named Credential, you write callout: followed by the Named Credential name, then any path and query string.
callout:Weather_API/forecast?city=OsloAt runtime Salesforce does three things:
- It replaces
callout:Weather_APIwith the base URL stored on the Named Credential. - It applies the authentication and custom headers from the linked External Credential.
- It checks that the running user has access to the External Credential principal.
Your code never contains the host name or a secret.
The callout in full
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();
}
}Points to notice:
- The Named Credential URL is
https://api.example.com/v1, so the final request goes tohttps://api.example.com/v1/forecast?city=Oslo. EncodingUtil.urlEncodeprotects the query string from spaces and special characters in thecityvalue.- You do not set an
X-Api-Keyheader. The credential configuration adds it. - The code checks the status code itself. A 4xx or 5xx response does not throw an exception. Only network-level failures do, such as a timeout or a missing credential.
How the request flows
Rules to remember
- The name after
callout:is the Named Credential's developer name, not its label. It is case-sensitive in practice, so copy it exactly. - Path and query are appended directly. Start the path with
/, and do not repeat the base path already stored on the credential. - You can use
POST,PUTand other methods the same way. Set the body withreq.setBody(). - The class uses
with sharing, but callout access does not depend on record sharing. It depends on the user's permission set. - A callout cannot run after uncommitted DML in the same transaction. Make the callout first, or move it to an asynchronous job.
Common mistakes
| Symptom | Likely cause |
|---|---|
| Error that the named credential cannot be found | Wrong name after `callout:` |
| 404 from the service | Base path duplicated or missing a leading `/` |
| Access or authentication error before the request leaves | User lacks principal access in a permission set |
| 401 from the service | Secret or header formula is wrong |
Exercise
A Named Credential Orders_API has the URL https://shop.example.com/api. Write the endpoint string for a GET request to https://shop.example.com/api/orders/42, and say why you do not set an Authorization header in the Apex code.
Show answer
The endpoint is callout:Orders_API/orders/42. The Authorization header comes from the External Credential linked to the Named Credential, which Salesforce applies at callout time, so the code needs neither the header nor the secret.