Let us understand what are Named Credentials in Salesforce and what are its Benefits
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.
Why Avoid Hardcoding Credentials :
- It is a Maintenance nightmare. Having Credentials hardcoded means you have to deploy the changes every single time like when your password changes or expires.
- It is also difficult to maintain changes in a different environment
- Not very secure.
Benefits of using Named Credentials :
- Authentication is done by Salesforce and you need not to worry about that.
- Easy for admins to maintain.
- Secure storage of credentials.
- No need to create a Remote Site Setting if using a Named Credential.
- The callout is easier to maintain. No hard coding involved.
Apex HTTP Callout Without Named Credential:
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://example .com/path/my/api');
String username = 'username';
String password = 'password';
//Add basic authentication header to the callout
Blob headerValue = Blob.valueOf(username + ':' + password);
String authHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authHeader);
Http h = new Http();
HttpResponse response = h.send(req);
System.debug('response-'+ response);
Apex HTTP Callout With Named Credential:
HttpRequest req = new HttpRequest();req.setMethod('POST');
req.setEndpoint('callout:Sample_API/some_path');
//No need to manually set any headers here. Salesforce will add this for us automatically.
Http http = new Http();
HTTPResponse response = http.send(req);
System.debug('response-'+ response);