Named Credentials – Code | Apex Callout

Are you concerned about exposing the URL to external system for integration and wish not to do so? Are you worried about sharing the Username / Password to connect with external system and how to hide it?  Then Named Credentials is the way to go and you are at right place to learn and know how to implement it!


A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. To simplify the setup of authenticated callouts, specify a named credential as the callout endpoint.

If you instead specify a URL as the callout endpoint, you must register that URL in your org’s remote site settings and handle the authentication yourself.

For example, for an Apex callout, your code would need to handle authentication, which can be less secure and especially complicated for OAuth implementations.

Difference Between Authentication Provider & Named Credentials

Developers usually gets confused between Authentication Provider & Named Credentials.  The difference is Authentication Provider is used for authenticating external application using OAuth where as Named Credentials is used to hide URL information from being exposed rather gives a short friendly name to use instead.

How to setup Named Credentials in Salesforce

Check how to Setup Named Credentials in Salesforce.  I’ve highlighted with Screenshots as well.

Setup Named Credentials in Salesforce

 How Named Credential Works?

– Direct way to make Callout in Apex

HttpRequest req = new HttpRequest();
// 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 ' +
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);

view raw


hosted with ❤ by GitHub

– Callout using Named Credentials

Syntax to use Named Credentials. In the following code snippet, we’re using SalesforceNC instead of ENDPOINT.

HTTPRequest feedRequest = new HTTP Request();
HTTP http = new HTTP();
HTTPResponse feedResponse = http.send(feedRequest);

Setup Named Credentials in Salesforce



2 Replies to “Named Credentials – Code | Apex Callout”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: