- Salesforce introduced Named Credentials in the Spring’15 release.
- Named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition.
- No need to handle Remote site settings of the Named credential callout URL.
- Named credentials separate the URL from the authentication, making it easier to make changes to both the endpoint URL and authentication if needed.
- It supports Basic Password authentication and OAuth 2.0 authentication protocols.
- You can configured Named credentials to use an org-wide named principal or to use per-user authentication so that users can manage their own credentials.
Apex HTTP Callout Without Named Credential:
String username = 'username'; String password = 'password'; String endpoint = 'https://testapi.com'; Http http = new Http(); HttpRequest req = new HttpRequest(); req.setMethod('POST'); req.setEndpoint(endpoint); //Add basic authentication header to the callout Blob headerValue = Blob.valueOf(username + ':' + password); String authHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue); req.setHeader('Authorization', authHeader); HttpResponse response = http.send(req); System.debug('response-' + response);
Example:
Setup | Quick Find – Search Named Credentials | New Named Credential
Create Named Credential as per your requirement:
Apex HTTP Callout With Named Credential:
Http http = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint('callout:Sample_API/some_path'); req.setMethod('POST'); HTTPResponse response = http.send(req); System.debug('response-' + response);