Sub topic 4
Named Credentials and the callout: prefix
This chapter explains how a Named Credential replaces a hard-coded URL and stored secrets in your Apex code. It covers how the callout: prefix resolves at runtime and which setup errors to expect. It assumes you can read basic Apex and know what an HTTP request and status code are. It also assumes you can create metadata in Setup and have seen Http, HttpRequest and HttpResponse.
Why Named Credentials exist
A callout needs three things that you should not scatter through code: the base URL, the authentication details, and permission from the platform to contact that host. Without a Named Credential, you would write something like this:
req.setEndpoint('https://jsonplaceholder.typicode.com/todos/1');
req.setHeader('Authorization', 'Bearer ' + someHardCodedToken);This has several problems:
- The URL is baked into the class, so moving from sandbox to production means a code change.
- The token lives in source control.
- The host needs a separate Remote Site Setting.
A Named Credential is a metadata record that stores the base URL and a reference to the authentication setup. Your code refers to it by name, and the platform fills in the rest at runtime.
The two-part model
Since Winter '23, the recommended setup splits the work between two records.
| Record | Holds | Typical question it answers |
|---|---|---|
| Named Credential | Base URL, the External Credential to use, optional callout options | Where do I send the request? |
| External Credential | Authentication protocol, one or more principals, custom headers and parameters | How do I prove who I am? |
| Permission set mapping | Which users may use which External Credential principal | Who may make this call? |
A principal is an identity the external system recognizes. A Named Principal uses one shared identity for everyone, such as a service account. A Per User Principal gives each Salesforce user their own identity, for example their own OAuth token.
The older, legacy Named Credential combined the URL and the authentication in one record. Legacy records still work, and you will meet them in older orgs. The callout: syntax in Apex is the same for both kinds.
Setup steps for the new model
- In Setup, create an External Credential. Choose a protocol, such as Basic, OAuth 2.0, or Custom for API keys and tokens.
- Add a principal and enter its secret values, such as a username and password or an API key.
- Create a Named Credential. Set the name to
Todo_API, the URL tohttps://jsonplaceholder.typicode.com, and select your External Credential. - Create or edit a permission set. Under External Credential Principal Access, enable the principal.
- Assign that permission set to every user who will run the callout, including integration users and the user who runs scheduled Apex.
Step 4 is the most common gap. The record exists and the code is correct, but the running user has no access to the principal, so the callout fails.
The callout: prefix
In Apex, you write the endpoint as callout: followed by the Named Credential's API name and then a path:
req.setEndpoint('callout:Todo_API/todos/1');At runtime, the platform does the following:
- It replaces
callout:Todo_APIwith the URL from the Named Credential. - It adds the authentication header or token that the External Credential defines.
- It adds any custom headers configured on the credential.
- It sends the request.
The result in this example is a request to https://jsonplaceholder.typicode.com/todos/1.
Using it in a full request
This class sends a GET through the credential. It also sets a custom header from Apex, which is separate from any headers configured on the External Credential.
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());
}
}The class contains no host name, no secret and no Remote Site Setting reference. To point it at a staging server, you change the Named Credential URL in Setup.
Path rules
The path you append is joined to the Named Credential URL. Keep these points in mind:
- If the Named Credential URL already ends with a path segment, such as
https://api.example.com/v2, your Apex path continues from there.callout:Svc/itemsbecomeshttps://api.example.com/v2/items. - Start the Apex path with
/after the credential name, and do not end the credential URL with a slash. Doubled slashes can produce 404 responses on strict servers. - Query strings go in the Apex string, for example
'callout:Todo_API/todos?userId=1'. URL-encode user-supplied values withEncodingUtil.urlEncode(). - A managed package that ships its own credential refers to it with the namespace:
callout:myns__Todo_API/....
Authentication merge fields
Sometimes you need a secret inside the header or body, not only in the standard Authorization header. Named Credentials support merge fields for this, in {!...} form.
For legacy Named Credentials with password authentication:
req.setHeader('X-Auth', '{!$Credential.Username}:{!$Credential.Password}');For the new model, you reference a parameter that you defined on the External Credential:
req.setHeader('X-Api-Key', '{!$Credential.Todo_Auth.ApiKey}');Here Todo_Auth is the External Credential's API name and ApiKey is the name of an authentication parameter on the principal. The platform substitutes the value when it sends the request, so the secret never appears in your Apex strings or debug logs.
Be careful with two details:
- Merge fields are resolved only for Named Credential callouts. If you try them on a plain URL, the literal text is sent.
- Check what your org's credential settings allow. Whether merge fields are allowed in the header or body depends on the "Allow Merge Fields in HTTP Header" and "Allow Merge Fields in HTTP Body" options on legacy credentials.
Named Credential versus Remote Site Setting
Both authorize outbound traffic, but they do different things.
| Aspect | Remote Site Setting | Named Credential |
|---|---|---|
| Authorizes the host | Yes | Yes, no separate Remote Site Setting needed |
| Stores the URL | No, your code holds the URL | Yes |
| Stores authentication | No | Yes, through the External Credential |
| Endpoint string in Apex | Full URL, such as `https://...` | `callout:Name/path` |
| Per-user access control | No | Yes, through permission sets and principals |
Use a Remote Site Setting only when you must call a raw URL, for example when the host name is computed at runtime. For a fixed service, a Named Credential is the better choice.
Deploying between orgs
The Named Credential and External Credential definitions deploy as metadata. The secret values do not. After deploying to a new org, you must:
- Open the External Credential and re-enter the principal's secrets, or re-run the OAuth authentication flow.
- Check that the permission set mapping came across.
- Confirm the Named Credential URL points at the correct environment.
A deployment that succeeds but gives 401 responses usually means the secrets were never entered in the target org.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Unauthorized endpoint" message mentioning Remote Site Settings | You used a full URL, or misspelled the credential so the prefix was not recognized | Use `callout:` with the exact API name, or add a Remote Site Setting for a raw URL |
| Failure that mentions the credential or principal not being found, or access denied | The running user's permission sets do not include the External Credential principal | Add principal access to a permission set and assign it |
| 401 or 403 from the remote service | Wrong or missing secret, expired token, or the secret was not entered after deployment | Re-enter the secret or re-authenticate the principal |
| 404 from the remote service | Doubled slash or a wrong base path in the Named Credential | Compare the final URL with the API documentation |
| Works for admins, fails for others | Only admins hold the principal access permission set | Assign the permission set to the other users |
| Works in the UI, fails in a scheduled job | The scheduled job runs as a user without principal access | Grant access to that user |
When debugging, remember that the platform does not show you the final URL in the exception. Compare what the remote service logs with what you expect.
Mocking and testing
Test code that uses callout: endpoints needs no real credential. Test.setMock intercepts the request before any lookup happens, so a mock works the same way as with plain URLs. Later chapters cover HttpCalloutMock in detail. Be aware that this also means a test passing says nothing about whether your credential and permissions are set up correctly. Verify that part manually in each org.
Exercise
A developer deploys a class using callout:Todo_API/todos from a sandbox to production. The Named Credential and External Credential deploy successfully, but the callout returns 401. The code did not change. What are two likely causes, and where do you check?
Show answer
First, the External Credential principal's secret was not entered in production, because secret values do not deploy as metadata. Check the principal on the External Credential and re-enter the secret or re-authenticate. Second, the Named Credential URL may still point at the sandbox or a different environment. Check the URL on the Named Credential. If the error were a permissions failure instead of a 401, you would check that the running user's permission set grants access to the principal.
Exercise
Why is req.setEndpoint('callout:Todo_API/todos/' + todoId) better than req.setEndpoint('https://jsonplaceholder.typicode.com/todos/' + todoId)?
Show answer
The Named Credential keeps the base URL and authentication out of the code, so you can change them per environment in Setup without editing Apex. It also authorizes the host without a separate Remote Site Setting and adds authentication at runtime, and it controls who may use the credential through permission sets.