Skip to main content

How to Use Named Credentials in Salesforce Apex: Step-by-Step Guide

Connecting Salesforce to external systems using HTTP callouts is a core integration task. However, hardcoding endpoint URLs, API keys, or basic authentication headers directly inside Apex code creates major security vulnerabilities and deployment headaches. Named Credentials solve this problem by securely managing endpoint URLs and authentication details entirely through Salesforce declarative Setup.

In plain words: A Named Credential acts as a secure container for an external web address and its login credentials. Instead of writing long URLs and secret API keys in Apex, you point your code to callout:Your_Named_Credential_Name and let Salesforce handle authentication automatically.
Named Credential

Prerequisites

  • Basic understanding of Salesforce administration and Setup navigation.
  • Familiarity with Apex object-oriented programming and HTTP callouts.
  • An active sandbox or Developer Edition org.

Step 1: Create the Named Credential

Before writing code, configure your external endpoint details inside Salesforce Setup:

Step-by-Step Setup:
  1. Navigate to Setup → Named Credentials.
  2. Click New Named Credential (or configure an External Credential for modern OAuth flows).
  3. Set the Label (e.g., My Named Credential) and Name (e.g., My_Named_Credential).
  4. Enter the target URL (e.g., https://api.example.com).
  5. Select the required Identity Type and Authentication Protocol (such as OAuth 2.0, Password Authentication, or Named Principal).
  6. Save the record. Salesforce will automatically bypass the need to add this domain to Remote Site Settings.

Step 2: Write the Apex Callout Class

With the Named Credential created, write an Apex class to invoke the endpoint. Reference the credential using the callout: prefix in the endpoint string.

public class NamedCredentialExample {
    public static void makeCallout() {
        // Initialize the HTTP Request object
        HttpRequest request = new HttpRequest();
        
        // Combine callout:NamedCredentialName with the API endpoint path
        request.setEndpoint('callout:My_Named_Credential/some/path');
        request.setMethod('GET');
        
        try {
            // Send the request
            HttpResponse response = new Http().send(request);
            
            // Check for successful status code
            if (response.getStatusCode() == 200) {
                System.debug('Success Response Payload: ' + response.getBody());
            } else {
                System.debug('Server Error. Status Code: ' + response.getStatusCode());
            }
        } catch (Exception ex) {
            System.debug('Callout Exception: ' + ex.getMessage());
        }
    }
}

Step 3: Execute the Callout

To run the method and test your integration, invoke it directly via Developer Console → Execute Anonymous:

NamedCredentialExample.makeCallout();
Developer Trap: Hardcoding Endpoints & API Keys! Storing secret keys, passwords, or explicit URLs directly inside Apex classes compromises security, breaks code when switching environments (Sandbox to Production), and requires editing code files whenever passwords rotate.
Core Integration Rule: Always use callout:Named_Credential_Name instead of raw URLs to automatically handle headers, authentication, and Remote Site Settings.
360 Card: Why Use Named Credentials?
  • Security: Keeps password/token management safely isolated in Setup; zero hardcoded secrets in Apex code.
  • Maintenance: Update endpoints or passwords instantly without editing or redeploying code.
  • Efficiency: Automatically bypasses standard Remote Site Settings configuration.
  • Authentication Support: Native handling for Basic Auth, OAuth 2.0, JWT, and Client Certificates.

Conclusion

Named Credentials decouple authentication details from your Apex codebase, significantly improving security, maintenance, and deployment speed. Adopting this pattern guarantees that API endpoint changes or password rotations can be handled instantly by system administrators without writing a single line of code.