Use the Named Credential in a Callout
With the credential defined, you can use it in a callout without managing authentication details in your code.
Example: Making a Callout with a Named Principal
Often, the external system provides the same functionality to all users. Here, we make a callout that converts a small bit of text to Markdown. This call doesn’t return different results for different users in the org.
1HTTP h = new http();
2HTTPRequest hr = new HTTPRequest();
3hr.setEndpoint('callout:githubAPI/markdown');
4hr.setMethod('POST');
5hr.setBody('{"text":"Hello **world**"}');Example: Making a Per-User Callout
When the external credential is configured with a per-user identity type, callouts automatically incorporate the context of the current user and pass their access token in the appropriate header. Here, the callout returns a list of GitHub Gists for the current user. Note that there’s no explicit handling of user context because that happens automatically.
1HTTP h = new http();
2HTTPRequest hr = new HTTPRequest();
3hr.setEndpoint('callout:githubAPI/gists');
4hr.setMethod('GET');
5hr.setHeader('Accept', 'application/vnd.github+json');