is live. Lifetime & Yearly plans on offer. thankful for you ๐Ÿงก

Get the Black Friday deal

Apex

Named Credentials in Salesforce: Setup and Use in Apex

Named credentials in Salesforce store an endpoint URL and its authentication. Set one up with an External Credential and call it from Apex.

By Teja, ex-Salesforce engineer ยท Updated November 24, 2026 ยท 9 min read

Apex

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 ApexRemote Site SettingNamed Credential + External Credential
What it doesPuts the URL and secret in a string in your classAllowlists a URL so Apex can call itStores the URL and authentication, adds auth at runtime
Handles authenticationYou write it yourselfNoYes
Secret visible in code and version controlYesNot applicableNo
Needs a Remote Site SettingYesIt is oneNo
Access controlAnyone who can run the codeNone beyond the allowlistPermission set access to the principal
Changing the endpoint per environmentEdit code and redeployEdit the settingEdit the Named Credential URL, no code change
OAuth token refreshYou build itNoHandled 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

  1. Open the External Credentials tab and click New.
  2. Label: Weather API. Name: Weather_API.
  3. Authentication Protocol: Custom.
  4. Save.

Step 2: Add a principal and store the secret

  1. On the External Credential, go to Principals and click New.
  2. Parameter Name: WeatherPrincipal. Identity Type: Named Principal. Use this when the whole org shares one API key.
  3. Under Authentication Parameters, add a parameter named ApiKey and paste the key as its value.
  4. 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

  1. On the same External Credential, go to Custom Headers and click New.
  2. Name: x-api-key.
  3. Value: {!$Credential.Weather_API.ApiKey}
  4. 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

  1. Open the Named Credentials tab and click New (not "New Legacy").
  2. Label: Weather. Name: Weather.
  3. URL: https://api.example-weather.com.
  4. Make sure Enabled for Callouts is on.
  5. External Credential: Weather API.
  6. 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: Bearer header for you.
  7. Allow Formulas in HTTP Header: turn this on if you use merge fields in headers set from Apex.
  8. 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.

  1. Create a permission set, for example Weather API Access, or open an existing one.
  2. Go to External Credential Principal Access and click Edit.
  3. Move Weather_API - WeatherPrincipal into Enabled.
  4. 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 implements Database.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 CredentialUse it whenNotes
CustomThe API uses API keys, static bearer tokens or other header-based authStore values as principal parameters and reference them in custom headers
OAuth 2.0, Client CredentialsServer-to-server integrations with no user in the loopOne Named Principal, and Salesforce fetches and refreshes the token
OAuth 2.0, JWT BearerThe provider trusts a signed JWT from a certificate you controlCommon for Salesforce-to-Salesforce and enterprise APIs
OAuth 2.0, Browser FlowEach user should act as themselves in the external systemPair with a Per User Principal
AWS Signature Version 4Calling AWS services such as S3 or API GatewaySalesforce 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

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts