A Named Credential in Salesforce is a piece of metadata that stores a callout endpoint's base URL. It links to an External Credential, which stores how to authenticate to that endpoint (OAuth, API key, custom headers). In Apex you send requests to callout:Your_Named_Credential/path, and Salesforce adds the URL and the auth details at runtime. Secrets never show up in your code, and you don't need a Remote Site Setting.
Below: setup for the current model (Named Credential plus External Credential), a working Apex example, the permission set step that breaks most first callouts, and how to test it.
What a Named Credential stores
Since Winter '23, Salesforce splits the job across two records.
Named Credential holds:
- The endpoint URL (for example
https://api.example.com) - A reference to the External Credential it uses
- Callout options: whether Salesforce generates the Authorization header, and whether formulas are allowed in HTTP headers and the body
External Credential holds:
- The authentication protocol (OAuth 2.0, AWS Signature Version 4, or Custom)
- One or more principals, which are the identities Salesforce authenticates as. A Named Principal uses one shared identity for everyone. A Per User Principal gives each user their own credentials.
- Authentication parameters stored on the principal, such as an API key or client secret
- Custom headers, which can reference those parameters with formulas
The split means several Named Credentials can share one External Credential. Typical case: a sandbox URL and a production URL that use the same auth setup. Access is then controlled through permission sets.
Older orgs may still have legacy Named Credentials, which stored the URL and auth in one record. Salesforce has deprecated them and recommends the new model for anything you build today. If you're maintaining an older integration, you'll see both under Setup.
Named Credentials vs Remote Site Settings vs hardcoded keys
These three get confused all the time because they all show up when someone writes their first callout.
| Hardcoded key in Apex | Remote Site Setting | Named Credential + External Credential | |
|---|---|---|---|
| What it does | Puts the URL and secret in a string in your class | Allowlists a URL so Apex can call it | Stores the URL and authentication, adds auth at runtime |
| Handles authentication | You write it yourself | No | Yes |
| Secret visible in code and version control | Yes | Not applicable | No |
| Needs a Remote Site Setting | Yes | It is one | No |
| Access control | Anyone who can run the code | None beyond the allowlist | Permission set access to the principal |
| Changing the endpoint per environment | Edit code and redeploy | Edit the setting | Edit the Named Credential URL, no code change |
| OAuth token refresh | You build it | No | Handled by Salesforce for supported OAuth flows |
A Remote Site Setting only tells Salesforce "this domain may be called." It knows nothing about who you are. A hardcoded key or a key in a Custom Setting works, but it ends up in Git, in debug logs, and in front of every developer with org access. A Named Credential keeps the secret in a store that Apex can't read directly. Salesforce puts it into the request just before sending.
Setting up a Named Credential: worked example
Example scenario: you call a weather API that authenticates with an x-api-key header. API key auth uses the Custom protocol.
All of this lives in Setup > Security > Named Credentials, which has two tabs: Named Credentials and External Credentials. Create the External Credential first, because the Named Credential has to point at it.
Step 1: Create the External Credential
- Open the External Credentials tab and click New.
- Label:
Weather API. Name:Weather_API. - Authentication Protocol: Custom.
- Save.
Step 2: Add a principal and store the secret
- On the External Credential, go to Principals and click New.
- Parameter Name:
WeatherPrincipal. Identity Type: Named Principal. Use this when the whole org shares one API key. - Under Authentication Parameters, add a parameter named
ApiKeyand paste the key as its value. - Save.
This value is encrypted, and after you save it nobody can read it back in plain text from Setup, Apex or the API.
Step 3: Add the custom header
- On the same External Credential, go to Custom Headers and click New.
- Name:
x-api-key. - Value:
{!$Credential.Weather_API.ApiKey} - Save.
The merge syntax is $Credential.<ExternalCredentialDeveloperName>.<ParameterName>. A bearer token works the same way. Name the header Authorization and set the value to Bearer {!$Credential.Weather_API.Token}.
Step 4: Create the Named Credential
- Open the Named Credentials tab and click New (not "New Legacy").
- Label:
Weather. Name:Weather. - URL:
https://api.example-weather.com. - Make sure Enabled for Callouts is on.
- External Credential:
Weather API. - Generate Authorization Header: you can leave this off here, because the Custom header from Step 3 handles auth. Turn it on for OAuth protocols, where Salesforce builds the
Authorization: Bearerheader for you. - Allow Formulas in HTTP Header: turn this on if you use merge fields in headers set from Apex.
- Save.
Step 5: Grant access through a permission set
Most failed first callouts fail at this step. Creating the credential does not give anyone permission to use it.
- Create a permission set, for example
Weather API Access, or open an existing one. - Go to External Credential Principal Access and click Edit.
- Move
Weather_API - WeatherPrincipalinto Enabled. - Save, then assign the permission set to every user whose context will make the callout.
For Per User Principals, users also need object access to User External Credentials so their own credentials can be stored. Each user then authenticates once from their personal settings.
"Every user whose context makes the callout" includes non-obvious users. Batch Apex runs as the user who submitted the job. Scheduled Apex runs as the user who scheduled it. Platform event triggers run as the Automated Process user unless you set a different running user in the subscriber configuration. If an integration user or scheduler doesn't have the permission set, the callout fails in production even though it worked for you in the sandbox.
Calling the Named Credential from Apex
The endpoint format is callout: followed by the Named Credential's API name, then any path and query string:
public with sharing class WeatherService {
public class WeatherException extends Exception {}
public static String getCurrentWeather(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Weather/v1/current?city='
+ EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(20000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new WeatherException(
'Weather API returned ' + res.getStatusCode() + ': ' + res.getBody()
);
}
return res.getBody();
}
}
What's missing is the point. The class has no domain, no API key, no header-building code and no Remote Site Setting. Salesforce resolves callout:Weather to https://api.example-weather.com, appends /v1/current?city=..., and adds x-api-key from the External Credential.
Two rules still apply:
- Callouts from triggers must be asynchronous. Wrap the call in a
@future(callout=true)method or a Queueable that implementsDatabase.AllowsCallouts. - You can't make a callout after uncommitted DML in the same transaction. Do the callout first, or move the DML or the callout into a separate async job.
If the running user lacks principal access, the error message says Salesforce couldn't access the credential and that you may not have the required permissions. When you see that message, check Step 5 before you touch any code.
Testing callouts that use Named Credentials
Apex tests can't make real callouts, so you mock the response with HttpCalloutMock. In tests the endpoint isn't resolved, so the request your mock receives still says callout:Weather/.... That's useful, because you can assert on it.
@IsTest
private class WeatherServiceTest {
private class WeatherMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
Assert.isTrue(req.getEndpoint().startsWith('callout:Weather/v1/current'),
'Should use the Weather named credential');
Assert.areEqual('GET', req.getMethod());
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setHeader('Content-Type', 'application/json');
res.setBody('{"city":"Bengaluru","tempC":27}');
return res;
}
}
@IsTest
static void returnsBodyOn200() {
Test.setMock(HttpCalloutMock.class, new WeatherMock());
Test.startTest();
String body = WeatherService.getCurrentWeather('Bengaluru');
Test.stopTest();
Assert.isTrue(body.contains('"tempC":27'));
}
}
Add a second mock that returns a 401 or 500 and assert that WeatherException is thrown. Testing only the success path is how teams reach 75% coverage without testing anything meaningful. The Apex Test Fest course covers callout mocks alongside async tests, System.runAs and the Assert class. System.runAs matters here if you want to prove that a user without the permission set can't make the call.
Choosing an authentication protocol
| Protocol on the External Credential | Use it when | Notes |
|---|---|---|
| Custom | The API uses API keys, static bearer tokens or other header-based auth | Store values as principal parameters and reference them in custom headers |
| OAuth 2.0, Client Credentials | Server-to-server integrations with no user in the loop | One Named Principal, and Salesforce fetches and refreshes the token |
| OAuth 2.0, JWT Bearer | The provider trusts a signed JWT from a certificate you control | Common for Salesforce-to-Salesforce and enterprise APIs |
| OAuth 2.0, Browser Flow | Each user should act as themselves in the external system | Pair with a Per User Principal |
| AWS Signature Version 4 | Calling AWS services such as S3 or API Gateway | Salesforce signs each request |
OAuth flows usually also need an Auth. Provider or connected-app setup on one side or the other. That's where most integration projects get complicated: the Named Credential is simple, and the OAuth handshake behind it is not.
Deployment: what moves between orgs and what doesn't
Named Credentials and External Credentials are metadata (NamedCredential and ExternalCredential), so you can deploy them with Salesforce DX, change sets or a CI pipeline. The secret values on principals are not deployed. After each deployment to a new org, and after sandbox refreshes where the values don't carry over, someone with admin access has to enter the API key or complete the OAuth authentication again. Permission set assignments also have to exist in the target org.
This is deliberate, and it's one of the main security wins. Your repository holds the shape of the integration, never the keys.
Where this fits before advanced integration work
Apex integrations build on Named Credentials. Once callout:Weather works, the next problems are bigger: OAuth handshakes with connected apps, JWT-signed server-to-server auth, exposing your own REST endpoints in Apex, publishing and subscribing to Platform Events, and moving large data volumes with Bulk API 2.0.
That's the scope of the Salesforce Integration Master Course. It's the largest course in the Salesforce Casts catalogue, and it covers OAuth, connected apps, Named and External Credentials, JWT, REST in Apex, Platform Events and Bulk API 2.0. Like every Salesforce Casts course, it's taught by Teja, an ex-engineer at Salesforce.com. The code is written live in a real org with no slide decks, and each course has a GitHub repo with the source. If you want the inbound side first, read how to create a REST API in Apex alongside this article.
If callouts are still new to you and Apex syntax slows you down, start with the Apex learning path and come back to integrations afterwards.
FAQ
Do I still need a Remote Site Setting if I use a Named Credential?
No. When the endpoint is callout:Your_Named_Credential, Salesforce treats the Named Credential's URL as allowed. You only need a Remote Site Setting for callouts that use a raw URL in setEndpoint.
Why does my callout fail with a credential access error when the setup looks right?
The running user almost always lacks External Credential Principal Access in a permission set. Check which user the code runs as. Scheduled jobs, batch jobs and platform event triggers often run as someone other than you. Assign the permission set to that user and try again.
Can I read the API key in Apex once it's stored on the principal?
No, and that's intentional. Apex can reference the value only through merge fields such as {!$Credential.Weather_API.ApiKey} in headers (or in the body, if you enable formulas there), and Salesforce resolves it when the request is sent. If code needs the raw secret, revisit the design.
Should I use a Named Principal or a Per User Principal?
Use a Named Principal when the integration acts as a system, with one key or service account for everyone. Use a Per User Principal when actions in the external system must be attributed to each Salesforce user, usually with an OAuth browser flow. Per-user setups also need object access to User External Credentials.
What happens to Named Credentials after a sandbox refresh or deployment?
The metadata moves, but the secrets don't, so an admin has to re-enter keys or re-authenticate OAuth in the target org. Build this into your deployment checklist, along with permission set assignments.
Are legacy Named Credentials still usable?
Existing legacy Named Credentials still work, but Salesforce has deprecated them in favor of the Named Credential plus External Credential model. Build new integrations on the new model and plan to migrate the old ones.
Next step
Create the Weather_API External Credential and the Weather Named Credential in a Developer Edition org, assign the permission set, and run the WeatherService class from Anonymous Apex. When it returns a 200, move on to OAuth and JWT in the Integration Master Course. Every plan on the pricing page unlocks it.
Learn it by building it
Every course, every code repository, the discussion group and certificates of completion โ one subscription.
Keep going
Blog
Apex Test Data Factory: A Reusable Pattern for Test Classes
Blog
Apex Trigger Interview Questions and Answers for Salesforce Developers
Blog
Governor Limits in Salesforce: What They Are and How to Stay Under Them
Blog
How to debug failures in Platform Events?
Blog
Retrying Failed Callouts in Salesforce Apex: Best Practices with Code Snippet
Blog
How to create REST API in Apex