Print this page

Spring '15 - Use Named Credentials as Endpoints to specify Authenticated Apex Callouts

Knowledge Article Number 000206791
Description A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. Salesforce manages all the authentication for Apex callouts that specify a named credential as the callout endpoint, so that your code doesn’t have to.
Resolution A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. Salesforce manages all the authentication for Apex callouts that specify a named credential as the callout endpoint, so that your code doesn’t have to. 

You can instead specify a URL as the callout endpoint and register that URL in your organization’s remote site settings. In that case,however, you handle the authentication in your code. Doing so can be less secure and especially complicated for OAuth authentication.

Example: In the following sample code, a named credential and an appended path specify the callout’s endpoint.
 
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());
 
You can code the callout endpoint as the URL instead of the named credential, but your code then handles the authentication. The example uses basic password authentication, but keep in mind that OAuth authentication is much more complex and best
handled with named credentials.
 
HttpRequest req = new HttpRequest();
req.setEndpoint('https://my_endpoint.example.com/some_path');
req.setMethod('GET');
// Specify the required user name and password to access the endpoint
// As well as 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: http://releasenotes.docs.salesforce.com/en-us/spring15/release-notes/rn_apex_named_credentials.htm




promote demote