Sub topic 4
Named Credentials and the callout: prefix
This chapter assumes you can write basic Apex, know HTTP methods and status codes, and can create metadata in Setup. It covers why Named Credentials exist, how to use one from Apex, and the errors you will most often see.
Why Named Credentials exist
A callout needs two things beyond the URL: permission to reach the host, and credentials the remote service accepts. If you hardcode both in Apex, you create problems:
- Secrets sit in source code and version control.
- The endpoint URL differs between sandbox and production, so you edit code at deploy time.
- You must add a separate Remote Site Setting for each host.
A Named Credential is a metadata record that stores the endpoint URL and the authentication settings in one place. Apex refers to it by name and never sees the secret.
What a Named Credential holds
A Named Credential combines these parts:
- URL: the base address of the external service, for example
https://jsonplaceholder.typicode.com. - Authentication: how Salesforce signs in. Common choices are no authentication, a username and password, or OAuth 2.0.
- Callout options: for example, whether Salesforce generates the authorization header for you.
Salesforce currently offers two forms. The newer form separates an External Credential (the authentication) from the Named Credential (the URL). The legacy form keeps both in a single record. The callout: syntax is the same for both.
The newer form also requires a permission set that grants users access to the External Credential principal. If this is missing, callouts fail for everyone except administrators.
Using the callout: prefix
In Apex, set the endpoint to callout: followed by the Named Credential's API name, then the path you want to call. Salesforce replaces the prefix with the stored URL and adds the authentication.
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());
}
}If Todo_API points to https://jsonplaceholder.typicode.com, this request goes to https://jsonplaceholder.typicode.com/todos/1. The code contains no host name and no credentials.
Named Credentials and Remote Site Settings
A callout to a Named Credential endpoint does not need a Remote Site Setting. The Named Credential itself authorizes the host. You need a Remote Site Setting only when you use a raw URL such as https://example.com/api. Prefer the Named Credential, because it also handles authentication and moves cleanly between orgs.
Setting one up
- In Setup, open Named Credentials.
- Create a new record. Give it a Label and a Name. The Name is the API name you use after
callout:, so keep it free of spaces, for exampleTodo_API. - Enter the base URL, with no trailing path.
- Choose the authentication settings. For a public test API, no authentication is fine.
- If you use the newer form, create the External Credential, add a principal, and grant access through a permission set.
- Save, then run the Apex above from Anonymous Apex.
Common errors
| Symptom | Likely cause |
|---|---|
| `Unauthorized endpoint, please check Setup->Security->Remote site settings` | You used a raw URL without a Remote Site Setting, or you misspelled the prefix, for example `callout/` instead of `callout:`. |
| `You have not been granted access to the external credential` | The running user lacks the permission set for the External Credential principal. |
| A 404 from the service | The Named Credential URL already includes a path, and the Apex path repeats it. |
| A 401 from the service | The authentication settings are wrong or the token has expired. |
Environments
Because Apex only holds the name, you can create a Todo_API record in each org with a different URL. Sandboxes then call test servers, and production calls the live service. The Apex class deploys unchanged. Keep in mind that secrets and tokens are not copied between orgs, so you must re-enter authentication after a sandbox refresh.
Exercise
A Named Credential called BillingAPI has the URL https://api.example.com/v2. Your Apex sets the endpoint to callout:BillingAPI/invoices/42. Which URL does the request go to, and do you need a Remote Site Setting for api.example.com?
Show answer
The request goes to https://api.example.com/v2/invoices/42. You do not need a Remote Site Setting, because the Named Credential authorizes the host.
Exercise
Why is it better to put the base URL in the Named Credential and the resource path in Apex, instead of the full URL in the Named Credential?
Show answer
One Named Credential can then serve many endpoints on the same service, and the code stays clear about which resource it calls. A full URL in the credential would force a separate credential for each resource.