Sub topic 10
Custom headers and credential formulas
This chapter assumes you can write a basic Apex callout, know how HTTP headers work, and have already created a Named Credential and an External Credential with a principal and permission set access. Here you will learn how the secret stored on the principal reaches the outgoing request without ever appearing in Apex.
The problem headers solve
Many APIs do not use the standard Authorization header. A weather service might want X-Api-Key: abc123. A partner API might want a tenant ID in X-Tenant, or a Basic-style token built from a user name and password. Salesforce can generate a standard Authorization header for OAuth and Basic authentication. For anything else you add custom headers and fill them with values from the credential.
A credential formula is a merge-style expression of the form {!$Credential...}. Salesforce evaluates it at callout time, on the server, and substitutes the real value into the request. Your Apex code, your logs and your metadata files contain only the formula text.
Where a custom header can be defined
You can define a custom header in Setup in two places:
- The Named Credential. The header describes the service, so it is added to every callout through that Named Credential.
- The External Credential. The header belongs to the authentication method, so it travels with that credential wherever it is used.
You can also set headers in Apex with setHeader. The next sections cover when that is appropriate.
| Where | Best for | Typical example |
|---|---|---|
| Named Credential custom header | Values every call to this service needs | `X-Api-Key` from a stored secret |
| External Credential custom header | Values tied to how you authenticate | A token header paired with the principal |
| `req.setHeader` in Apex | Values that change per request | `Accept`, `Content-Type`, a correlation ID |
A good rule is that headers the caller chooses per request stay in Apex. Headers that carry secrets or fixed service settings move to Setup.
The formula syntax
The formula that reads an authentication parameter has this shape:
{!$Credential.<ExternalCredentialDeveloperName>.<ParameterName>}In the chapter's running example, the External Credential Weather_EC has a principal with a parameter named ApiKey. The custom header on the Named Credential then looks like this:
Named Credential: Weather_API
Custom Header:
Name: X-Api-Key
Value: {!$Credential.Weather_EC.ApiKey}When Apex calls callout:Weather_API/forecast?city=Oslo, Salesforce does the following:
- It checks that the running user has access to the principal through a permission set.
- It looks up the
ApiKeyparameter stored on that principal. - It substitutes the value into
X-Api-Key. - It sends the request.
If step 1 fails, the formula is never resolved and the callout fails.
Building values with functions
Formulas can combine parameters and functions. The most common case is Basic authentication on an API that expects the encoded value in a custom header. The Custom authentication protocol lets you define your own parameters, so you can store the user name and password separately:
External Credential: Partner_EC
Authentication Protocol: Custom
Principal: Partner_Principal (Named Principal)
Authentication Parameter: Username = <entered in Setup>
Authentication Parameter: Password = <secret entered in Setup>
Named Credential: Partner_API
URL: https://partner.example.com/api
External Credential: Partner_EC
Custom Header:
Name: X-Partner-Auth
Value: Basic {!BASE64ENCODE($Credential.Partner_EC.Username & ':' & $Credential.Partner_EC.Password)}BASE64ENCODE and the & concatenation operator work as they do in Salesforce formula fields. Keep expressions short. A long formula is hard to read and hard to debug when the API answers 401.
If the API uses ordinary Basic or OAuth authentication, you don't need this. Leave Generate Authorization Header enabled on the Named Credential and Salesforce builds the Authorization header for you. Disable that option only when you supply the header yourself, otherwise the API may receive two competing authorization values.
Formulas in Apex headers and bodies
Sometimes you want Apex to decide which header to send, but still avoid handling the secret. The Named Credential has two opt-in settings for this:
- Allow Formulas in HTTP Header
- Allow Formulas in HTTP Body
With the first one enabled, Apex can put a formula in a header value, and Salesforce resolves it when the request is sent:
public with sharing class WeatherService {
public static String getForecastWithHeaderFormula(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');
// Resolved by Salesforce at send time. Apex never sees the key.
req.setHeader('X-Api-Key', '{!$Credential.Weather_EC.ApiKey}');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Weather API returned status ' + res.getStatusCode());
}
return res.getBody();
}
}The body option works the same way. You might send {"user":"{!$Credential.Partner_EC.Username}"} in a JSON payload when an API wants an account identifier inside the body.
What you can and cannot read
Secret authentication parameters are write-only in Setup. After you save the value, Salesforce shows it masked and you cannot read it back. Apex cannot read it either: there is no Credential.getValue() call. The only route from secret to API is the formula, resolved by the platform.
This has practical consequences:
- If you lose the secret, you re-enter it. You cannot recover it from the org.
- Debug logs show the formula text in your
setHeadercall, not the resolved value. This keeps logs safe, but it means you can't confirm the value by logging it. - A header that looks correct in the log can still fail if the parameter name is mistyped.
Testing with custom headers
HttpCalloutMock receives the request before any formula is resolved, because tests make no real callout. You can assert on what Apex set explicitly:
@IsTest
private class WeatherHeaderTest {
private class HeaderMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
System.assertEquals('application/json', req.getHeader('Accept'));
System.assertEquals('{!$Credential.Weather_EC.ApiKey}',
req.getHeader('X-Api-Key'));
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"temp":21}');
return res;
}
}
@IsTest
static void sendsFormulaHeader() {
Test.setMock(HttpCalloutMock.class, new HeaderMock());
Test.startTest();
String body = WeatherService.getForecastWithHeaderFormula('Oslo');
Test.stopTest();
System.assertEquals('{"temp":21}', body);
}
}A header defined only on the Named Credential in Setup never appears on req in a test, so you can't assert on it. The test confirms your Apex logic. Only a real callout in a sandbox confirms the Setup configuration.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| API returns 401 and the header looks right | Parameter name in the formula differs from the principal's parameter | Compare the name character by character, including case |
| The API receives the literal text `{!$Credential...}` | Formulas are not allowed for headers or the body on this Named Credential | Enable the matching option, or move the header to Setup |
| Two authorization values are sent | A custom `Authorization` header plus **Generate Authorization Header** | Disable generation, or remove the custom header |
| Callout fails before reaching the API | The user lacks permission set access to the principal | Add external credential principal access to a permission set |
| Header works in one org and not another | Secret values were not entered after deployment | Re-enter the parameters in the target org |
The last row anticipates the deployment chapter. Metadata moves between orgs, but secrets do not.
Exercise
A Named Credential has the custom header X-Api-Key with the value {!$Credential.Weather_EC.ApiKey}. A user calls the service, and the API replies 401. Name two things to check in Setup, and say why logging the header in Apex will not help you.
Show answer
Check that the parameter in the formula (ApiKey) exactly matches the authentication parameter name on the principal of Weather_EC, and check that the user has external credential principal access to that principal through a permission set. Also confirm the secret was entered correctly, since it can only be re-entered, not viewed. Logging the header will not help because Apex only holds the formula text. Salesforce substitutes the real value after Apex hands off the request, so the log never shows the resolved secret.
Exercise
You want Apex to set X-Api-Key with req.setHeader using a credential formula. Which Named Credential setting must be enabled, and what do you lose by enabling it?
Show answer
Enable "Allow Formulas in HTTP Header" on the Named Credential. In exchange, Apex code in the org can now reference credential values through formulas on that Named Credential, so you must review any code that builds header values from untrusted input. If the header is fixed, defining it on the Named Credential in Setup avoids this exposure.