Sub topic 4
Using Named Credentials for the endpoint
This chapter covers how the callout in our trigger-driven pattern finds its endpoint and authenticates, without any URL or secret in Apex code. It assumes you can write basic Apex classes and an HttpRequest/Http/HttpResponse callout. It also assumes you have the previous chapter's refresher in mind and are comfortable with permission sets. You do not need to know the async patterns yet. The Queueable and future chapters reuse the code from this one.
Why not hardcode the endpoint
A callout needs two things beyond the request body: an address and credentials. The quickest approach is to write both in Apex:
req.setEndpoint('https://billing.example.com/api/accounts');
req.setHeader('Authorization', 'Bearer abc123...');This causes several problems:
- The secret is in source control, in every sandbox copy, and visible to anyone who can read the class.
- Moving from sandbox to production means a code change, because the host differs per org.
- Each new endpoint host must be added to Remote Site Settings, or the callout fails.
- Token refresh and expiry are your problem.
A Named Credential moves all of this out of code and into org configuration. Your Apex refers to the endpoint by name, and the platform supplies the host and the authentication at runtime.
What a Named Credential is
A Named Credential is a metadata record that stores the base URL of an external system and a reference to how to authenticate to it. In Apex you build the endpoint with the callout: prefix:
callout:Billing_API/accountsThe platform splits this string. Billing_API is the Named Credential's developer name. /accounts is a path appended to the credential's base URL. If the base URL is https://billing.example.com/api/v2, the request goes to https://billing.example.com/api/v2/accounts.
Callouts that use callout: do not need a Remote Site Setting. The Named Credential itself authorizes the host.
The two models: legacy and current
Salesforce has two ways to configure Named Credentials. You will meet both in real orgs.
| Aspect | Legacy Named Credential | Current model (Named Credential + External Credential) |
|---|---|---|
| Where authentication lives | Inside the Named Credential | In a separate External Credential |
| Authentication protocols | Password, OAuth 2.0, JWT, JWT token exchange, AWS Signature v4, no authentication | Defined on the External Credential (for example OAuth 2.0, custom headers, AWS Signature v4, basic) |
| Who may use it | Based on identity type and the user's access to the credential | Based on permission sets mapped to an External Credential principal |
| Apex endpoint string | `callout:Name/path` | `callout:Name/path` |
The Apex endpoint string is the same in both. That is deliberate. You can migrate a credential to the current model without changing the setEndpoint call.
In the current model, three pieces fit together:
- The External Credential holds the authentication protocol and one or more principals. A principal represents an identity used to authenticate, such as a named service account.
- The Named Credential holds the base URL and points at the External Credential.
- A permission set grants users access to the External Credential principal. Without this, the callout is refused for that user.
The legacy model has an identity type setting. Named Principal uses one shared identity for every user. Per User makes each user authenticate separately. Per-user credentials are a poor fit for trigger-driven background work, which this tutorial covers below.
Building the request in one place
Because the same endpoint is used from a future method, a Queueable and perhaps a Batch job, it helps to build requests in one small class. This keeps the Named Credential name in a single constant.
public with sharing class BillingApiClient {
@TestVisible
private static final String ENDPOINT_ROOT = 'callout:Billing_API';
public static HttpRequest buildPost(String path, String jsonBody) {
HttpRequest req = new HttpRequest();
req.setEndpoint(ENDPOINT_ROOT + path);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(jsonBody);
return req;
}
public static HttpResponse send(HttpRequest req) {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR,
'Billing API error ' + res.getStatusCode() + ': ' + res.getBody());
}
return res;
}
}Notice what is absent. There is no host name, no Authorization header, and no token. The platform adds authentication after your code hands over the request. Your Apex cannot read the secret, and neither can anyone reading your logs.
A caller then looks like this:
HttpRequest req = BillingApiClient.buildPost('/accounts', JSON.serialize(payload));
HttpResponse res = BillingApiClient.send(req);Using the helper in the Queueable from the earlier outline is a two-line change in place of the manual request setup.
Merge fields for custom headers and bodies
Sometimes the remote API wants a value in a header or body that you can configure but should not hardcode, such as an API key or a username. Named Credentials support merge fields for this, so the secret stays in configuration.
In the legacy model, with password authentication, you can write:
req.setHeader('X-Api-User', '{!$Credential.Username}');In the current model, you define a custom header on the External Credential or Named Credential and reference its parameters with a formula such as {!$Credential.Billing_External.ApiKey}. The exact set of fields depends on the protocol. Check the setup UI for the names that apply to yours.
Two limits to keep in mind:
- Merge fields only resolve for requests that use a
callout:endpoint. Elsewhere they are sent as literal text. - The credential name in the formula must match the External Credential, not the Named Credential, in the current model.
Which user's access applies in async code
This is the part that surprises people in trigger work. The callout does not run in the trigger. It runs later in a Queueable or future method. That async code runs in the context of the user whose action started it. If a sales rep inserts an Account, the job executes as that rep.
So the check "does this user have access to the credential" is made against the rep, not against an admin. If the rep's permission set does not grant the External Credential principal, the callout fails at run time. The trigger and the enqueue both succeed, and only the later job fails.
Plan for this in one of these ways:
- Assign a permission set with the principal to every profile that can cause the trigger to fire. This suits a shared Named Principal credential.
- Avoid Per User identities for this pattern. Each user would need to authenticate to the remote system before saving a record, which is not realistic for records created by integrations and automated processes.
- Test as a user with the realistic permissions, not only as an admin.
Testing with Named Credentials
Unit tests cannot make real callouts, with or without Named Credentials. You still use Test.setMock with an HttpCalloutMock, as in the testing chapter. The mock intercepts the request after the endpoint string is built, so you can assert that the code used the correct Named Credential.
@IsTest
private class BillingApiClientTest {
private class CapturingMock implements HttpCalloutMock {
public HttpRequest captured;
public HttpResponse respond(HttpRequest req) {
captured = req;
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void usesNamedCredentialEndpoint() {
CapturingMock mock = new CapturingMock();
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
HttpRequest req = BillingApiClient.buildPost('/accounts', '[]');
HttpResponse res = BillingApiClient.send(req);
Test.stopTest();
System.assertEquals(200, res.getStatusCode());
System.assertEquals('callout:Billing_API/accounts', mock.captured.getEndpoint());
System.assertEquals('POST', mock.captured.getMethod());
}
}The test checks that the endpoint begins with the credential prefix. It does not check that the credential exists in the org, because the mock replaces the real send. Existence and permissions are verified only by a real callout in a sandbox, so include a manual or integration check when you deploy.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| Callout fails with an exception naming the Named Credential as not found or inaccessible | Wrong developer name in `callout:`, credential not deployed to this org, or user lacks permission set access | Check the exact name (case matters in practice), deploy the metadata, assign the permission set |
| Callout works for admins but fails for regular users in the async job | Principal access granted only to admin permission sets | Grant the permission set to everyone who can cause the trigger to fire |
| Callout to the right host returns 401 or 403 | Credential configured, but token or API key is wrong or expired in the External Credential | Update the principal's authentication, then retest |
| Merge field text appears literally in the remote system's logs | Request did not use a `callout:` endpoint | Move the host into the Named Credential and use `callout:` |
| Works in sandbox, wrong host in production | Different credential URL per org was expected, but the metadata was deployed with the sandbox URL | Update the URL in each org after deployment, or use a deployment process that substitutes it |
Design decisions
Using a separate Named Credential per external system is better than one per environment variable. The credential name stays the same in every org, and only its URL and secrets differ. Your code and tests are then identical everywhere.
Keep the path in Apex and the host in the credential. Paths belong to your code because they describe which operation you are calling. Hosts belong to configuration because they vary by environment.
Exercise
A trigger on Account enqueues a Queueable that posts to callout:Billing_API/accounts. The callout works when an administrator inserts an Account in a sandbox, but fails when a sales user does. The trigger and enqueue succeed in both cases. What is the most likely cause, and what is the fix?
Show answer
The async job runs as the user who inserted the record, and the sales user has no permission set granting access to the External Credential principal behind Billing_API. The admin has access, so the callout works for them. Fix it by assigning a permission set that grants the principal to every user who can cause the trigger to fire (and test as such a user). The Apex code does not need to change.