REST API Integration using Named Credentials:
by AR Designs
3 months ago
0
A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. Salesforce manages all authentication for Apex callouts that specify a named credential as the callout endpoint so that your code doesn’t have to. You can also skip remote site settings, which are otherwise required for callouts to external sites, for the site defined in the named credential.
To integrate a REST API with named credentials in Salesforce, you can follow these steps:
1. Create a Named Credential:
- Go to Setup in Salesforce.
- In the Quick Find box, search for "Named Credentials" and select it.
- Click on "New Named Credential" and fill in the necessary details.
- Specify the URL of the REST API endpoint you want to integrate with.
- Choose the appropriate authentication method (e.g., OAuth, JWT, etc.) and provide the required authentication details.
- Save the Named Credential.
2. Define Remote Site Settings:
- In the Quick Find box, search for "Remote Site Settings" and select it.
- Click on "New Remote Site" and provide a name and the URL of the REST API endpoint.
- Save the Remote Site Settings.
3. Use the Named Credential in Apex:
- In your Apex code, you can use the Named Credential to make REST API requests.
- Use the HttpRequest class to create an HTTP request instance.
- Set the endpoint URL as the Named Credential URL.
- Set the method (GET, POST, etc.) and any required headers and parameters.
- Use the Http class to send the request and receive the response.
HttpRequest req = new HttpRequest();
req.setEndpoint(‘callout:My_Named_Credential/path/to/api’);
req.setMethod(‘GET’);
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
// Process the response
String responseBody = res.getBody();
// …
} else {
// Handle error
String errorMessage = ‘Error: ‘ + res.getStatusCode() + ‘ – ‘ + res.getStatus();
// …
}
req.setEndpoint(‘callout:My_Named_Credential/path/to/api’);
req.setMethod(‘GET’);
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
// Process the response
String responseBody = res.getBody();
// …
} else {
// Handle error
String errorMessage = ‘Error: ‘ + res.getStatusCode() + ‘ – ‘ + res.getStatus();
// …
}