Sub topic 3
The Named Credential: where the service lives
This chapter assumes you can write a basic Apex class and send an HttpRequest. It also assumes you know your way around Setup and permission sets, and that you know what a base URL, header and status code are. Authentication is covered in the next chapter, so here it appears only as a reference to an External Credential.
What a Named Credential holds
A Named Credential is a Setup record that stores the location of an external service and a few settings that control how callouts to it behave. Its main job is to answer one question: where does this service live?
It holds three kinds of information:
- The base URL of the service, such as
https://api.example.com/v1. - A link to exactly one External Credential, which defines how Salesforce authenticates.
- Callout options, such as whether Salesforce generates the
Authorizationheader and whether formulas are allowed in headers or the body.
Because the record has a name, your Apex code can say callout:Weather_API instead of a full URL. The name is the only thing the code needs to know.
How Salesforce resolves a callout: endpoint
When Apex sends a request whose endpoint starts with callout:, the platform takes the text after callout: up to the first / as the Named Credential name. It replaces that prefix with the stored base URL. Then it asks the linked External Credential for authentication data and adds it to the request.
The base URL and the path you supply are joined into one URL. With a base URL of https://api.example.com/v1, the endpoint callout:Weather_API/forecast?city=Oslo becomes https://api.example.com/v1/forecast?city=Oslo.
Your code cannot change the host. It can only add a path and query string after the stored base URL. This is a security benefit: a bug or a user-supplied value cannot redirect a credential-bearing request to a different server.
Fields you set
Open Setup, search for Named Credentials, and create a new record on the Named Credentials tab. These are the fields that matter.
| Field | Purpose | Notes |
|---|---|---|
| Label | Display name in Setup | Free text. |
| Name | The name used after `callout:` | Letters, numbers and underscores. Treat it as an API name that code depends on. |
| URL | Base URL of the service | Use HTTPS. Include a version prefix such as `/v1` here if every call needs it. |
| Enabled for Callouts | Master switch | If cleared, callouts that use this record fail. |
| External Credential | Authentication definition | One Named Credential links to one External Credential. Several Named Credentials can share the same External Credential. |
| Generate Authorization Header | Let Salesforce build `Authorization` | Typical for Basic and OAuth. Clear it if the API expects a different header. |
| Allow Formulas in HTTP Header / Body | Permit `{!$Credential...}` merge fields | Needed when you inject a secret into a custom header or body. |
| Custom headers | Fixed headers added to every request | Useful for API versions or static identifiers. |
A short outline of a typical record, using the names from this tutorial:
Named Credential: Weather_API
URL: https://api.example.com/v1
Enabled for Callouts: checked
External Credential: Weather_EC
Generate Authorization Header: cleared (API uses X-Api-Key)
Allow Formulas in HTTP Header: checkedChoosing what goes in the base URL
Put in the base URL what never changes across calls: scheme, host, and any fixed prefix like /v1. Put in Apex what varies per call: the resource path and query parameters.
Two practical rules follow from this:
- Do not end the base URL with a query string. Parameters belong in the request so each call can set its own.
- Keep the path in Apex starting with
/. The endpointcallout:Weather_API/forecastis clear. Leaving out the slash joins the path to the base URL without a separator and produces a broken URL.
The next example sends a POST request through a Named Credential named Orders_API, which has the base URL https://api.example.com/v2.
public with sharing class OrderService {
public static Integer createOrder(String sku, Integer quantity) {
Map<String, Object> payload = new Map<String, Object>{
'sku' => sku,
'quantity' => quantity
};
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(payload));
req.setTimeout(20000);
HttpResponse res = new Http().send(req);
return res.getStatusCode();
}
}The request goes to https://api.example.com/v2/orders. Nothing in the class mentions a host, a password or a token. Authentication is added by Salesforce after this code runs.
One name, a different URL per org
The strongest everyday benefit of a Named Credential is environment separation. The sandbox and production orgs can both have a Named Credential called Orders_API. The sandbox record points at https://sandbox.api.example.com/v2, and the production record points at https://api.example.com/v2.
The Apex class is identical in both orgs. You deploy the class once and configure the URL separately. Without this, you would need custom settings or if (isSandbox) logic to pick the right host. Chapter material on deployment covers how the metadata moves. For now, the point is that the URL is configuration, not code.
No Remote Site Setting required
An Apex callout to a plain URL is blocked unless an admin adds that host to Remote Site Settings. A callout through a Named Credential does not need that entry. The Named Credential already declares the allowed destination, and it is the only place you maintain it.
If an old class uses a raw URL and also has a Remote Site Setting, switching to callout: lets you delete that Remote Site Setting once nothing else uses it.
Common errors with Named Credentials
Most failures at this stage come from a mismatch between the name in code and the record in Setup, or from settings on the record.
| Symptom | Likely cause | Fix |
|---|---|---|
| Exception saying the named credential cannot be found | The name after `callout:` does not match the record's Name, or the record is in another org | Check the exact spelling in Setup. Confirm the record was deployed. |
| Exception saying you cannot access the credential, or that it does not exist | The running user lacks permission set access to the External Credential principal | Grant access in a permission set. This is covered in a later chapter. |
| Request reaches the wrong path, such as a 404 on `/v1forecast` | Missing `/` after the credential name | Write `callout:Weather_API/forecast`. |
| 401 or 403 from the API with a correct URL | Authorization header is generated when the API expects a custom one, or the reverse | Adjust Generate Authorization Header and custom headers. |
| Callout fails immediately with a disabled message | Enabled for Callouts is cleared | Select it. |
| Literal `{!$Credential...}` text arrives at the API | Formulas not allowed in headers or body | Select the matching Allow Formulas option. |
Exact error wording varies by release, so match on the cause, not on the message text.
Where else the name is used
The callout: syntax is not limited to Apex HttpRequest. The same Named Credential can back Flow HTTP callouts and External Services. Defining the service once means each tool shares the same URL and authentication setup.
Exercise
A Named Credential Orders_API has the URL https://api.example.com/v2. An Apex class sets the endpoint to callout:Orders_API/orders?status=open. What URL does the request go to, and why can't the class send it to a different host by editing the string after callout:Orders_API?
Show answer
The request goes to https://api.example.com/v2/orders?status=open. The platform replaces callout:Orders_API with the stored base URL, so the host comes from the Named Credential, and Apex can only append a path and query string after it. That keeps credentials from being sent to a server the administrator did not approve.
Exercise
Production and sandbox must call different hosts from the same Apex class. How do you set that up with Named Credentials, and what must stay the same in both orgs?
Show answer
Create a Named Credential with the same Name in both orgs, and give each a different URL, for example the sandbox host in the sandbox org and the production host in production. The Name must match in both orgs because the Apex code refers to it as callout:Name. The class itself needs no changes.