Securing Callouts with Named Credentials
By the end of this lesson, you'll be able to:
- Explain what a Named Credential does and why it's preferred over hardcoding auth
- Make a callout using a Named Credential endpoint
Prerequisites: Building a Custom Apex REST Service
Why not just hardcode a token?
Hardcoding an API key or bearer token in Apex means it's visible in code, hard to rotate, and gets deployed and version-controlled alongside your source — a real security risk. A Named Credential moves that secret into Setup, managed separately from code, and it never appears in a class body or in version control.
Using a Named Credential in a callout
req.setEndpoint('callout:My_Named_Credential/v1/orders');
The callout: prefix tells Salesforce to look up the base URL and inject the configured authentication automatically — no setHeader('Authorization', ...) needed in your code at all.
A callout with no visible secrets
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Weather_API/v1/current?city=CapeTown');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
No API key appears anywhere in this code — Weather_API is a Named Credential configured once in Setup, and Salesforce attaches the right auth header automatically for every callout that uses it.
Exercise
Rewrite this callout to use a Named Credential named 'Orders_API' instead of a hardcoded URL and Authorization header.
Show hint
req.setEndpoint('callout:Orders_API/v1/orders'); — and delete the setHeader('Authorization', ...) line entirely.
Securing Callouts with Named Credentials — Quick Check
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A Named Credential stores an external endpoint's URL and authentication details (API key, OAuth) in Setup, separate from your code — Apex references it by name and Salesforce injects the auth automatically, so no secrets ever appear in your codebase.