Named Credentials in Salesforce

Ranbir Kumar Das
Salesforce Champion
2 min readApr 9, 2023
Salesforce Named Credentials

A named credential specifies an endpoint callout URL and its required authentication settings in its definition. The named credential helps you avoid writing the same call over and over again.

Named credentials are supported in these types of callout definitions.

  • Apex callouts
  • External data sources
  • External Services

Syntax: callout:My_Named_Credential/some_path?format=json

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Named_Credential/some_path');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());

//***********Reference from salesfroce developer************//

If we do not go for the named credential we need to write the below code and it also reduces the code complexity and also the complication of changes in apex code.

HttpRequest req = new HttpRequest();
req.setEndpoint('https://my_endpoint.example.com/some_path');
req.setMethod('GET');

// Because we didn't set the endpoint as a named credential,
// our code has to specify:
// - The required username and password to access the endpoint
// - The header and header information

String username = 'myname';
String password = 'mypwd';

Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);

// Create a new http object to send the request object
// A response object is generated as a result of the request

Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());

//*************Reference from salesforce developer**************//

To use the Named Credential we have to know about the auth provider.

Auth provider: Auth provider allows the third party to login into Salesforce login.

How to configure Auth provider please Read here.

Advantages of using the Named Credential

  1. No need to use the remote site setting.
  2. Reduce the code complexity of writing for authorization
  3. Easy to maintain and change in one place make an impact everywhere.
  4. With the help of a named credential, we do not need to use the username/password/token/secret in our code.

--

--

Ranbir Kumar Das
Salesforce Champion

I M Believer, Helper, Chaser, Thinker, Rich, Explorer, Prayer, Boss, Freedom, Fearless, Investor, Faith, Creator, trillionaire, CSM, Salesforce certified