Notes
To make a callout using named credentials in Salesforce, you need to modify your code and set up a named credential in Salesforce. Named credentials allow you to specify the endpoint URL, authentication, and other settings externally, so you don't need to hardcode them in your Apex code.
Steps to Set Up Named Credentials
Create a Named Credential:
- Go to Setup in Salesforce.
- In the Quick Find box, type Named Credentials and click on Named Credentials.
- Click New Named Credential.
- Fill in the required fields:
- Label:
CurrencyRateAPI
- Name:
CurrencyRateAPI
- URL:
http://apilayer.net
- Identity Type:
Anonymous
(since your endpoint doesn't require authentication) or choose the appropriate authentication method.
- Authentication Protocol:
No Authentication
(or as required).
- Leave the other fields as default or fill them out as necessary.
- Click Save.
public class CurrencyRateAPI {
public static void getExchangeRates2() {
Http http = new Http();
HttpRequest request = new HttpRequest();
// Use the Named Credential here
request.setEndpoint('callout:CurrencyRateAPI/api/live?access_key=33c1d301adec2998ab9fd71e7fdfc521¤cies=EUR,GBP,CAD,PLN&source=USD&format=1');
request.setMethod('GET');
HttpResponse response = http.send(request);
if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) {
System.debug(response.getBody().toString());
} else {
System.debug('Error: ' + response.getStatusCode() + ' - ' + response.getStatus());
}
}
}
Explanation:
- Named Credential: This allows you to manage the endpoint and credentials centrally without hardcoding them in your Apex code.
- callout
: Refers to the named credential you created. Salesforce replaces this with the actual endpoint URL when the callout is made.
This approach makes your code more secure and easier to manage. If the endpoint or credentials change, you can update them in the named credential without modifying the Apex code.