Sub topic 1
Apex Callouts with Named and External Credentials
Prerequisites
Assume you know basic Apex classes, HTTP methods and headers, and Salesforce permission sets. You should also know that an API key is a secret used to identify a caller.
Apex callouts in brief
An Apex callout is an HTTP request from Salesforce to an external service. Http sends the request. HttpRequest describes the method, endpoint, headers, and body. HttpResponse contains the status code, headers, and response body.
public with sharing class WeatherService {
public static String getForecast(String city) {
HttpRequest request = new HttpRequest();
request.setEndpoint(
'callout:Weather_API/forecast?city=' +
EncodingUtil.urlEncode(city, 'UTF-8')
);
request.setMethod('GET');
request.setHeader('Accept', 'application/json');
HttpResponse response = new Http().send(request);
if (response.getStatusCode() != 200) {
throw new CalloutException(
'Weather API returned status ' + response.getStatusCode()
);
}
return response.getBody();
}
}The callout: prefix tells Salesforce to resolve the endpoint through a Named Credential. The Apex code does not contain the service's real URL or secret.
Why credentials should not live in Apex code
Hardcoding a URL, API key, or password creates security and maintenance problems:
- Secrets can enter source control and deployment logs.
- Rotating a key requires a code change.
- Different environments may need different endpoint URLs.
- Developers may receive access to secrets they do not need.
Configuration keeps these values outside application code.
The Named Credential: where the service lives
A Named Credential identifies the external service. It stores the base URL and callout settings. In the example, Weather_API might point to https://api.example.com/v1.
The External Credential: how you authenticate
An External Credential defines how Salesforce authenticates. It can describe OAuth, API-key, Basic authentication, or another supported protocol. It contains one or more principals, which represent the credential identity used for the callout.
A Named Credential answers, “Where is the service?” An External Credential answers, “How does Salesforce authenticate?” Permission sets later decide which users may use a principal.
Exercise
What is the difference between a Named Credential and an External Credential?
Show answer
A Named Credential stores the service location and callout settings. An External Credential defines authentication and its principals.