Hardcoded callouts authentication
Why is this an issue?
Hardcoding endpoint URLs and authentication credentials in Apex code creates several problems:
Security risk: Credentials in code can be exposed through version control or logs.
Maintenance burden: Changing endpoints requires code changes and deployments.
Environment issues: Different environments (sandbox vs. production) often need different endpoints.
No credential rotation: Updating passwords requires code changes.
Named Credentials solve these problems by storing endpoint URLs and authentication details securely in Salesforce configuration.
Examples
Example of incorrect code:
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/data');
request.setHeader('Authorization', 'Bearer ' + apiKey);
request.setMethod('GET');
HttpResponse response = http.send(request);
Example of correct code:
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Example_API/data');
request.setMethod('GET');
// Authentication is handled automatically by the Named Credential
HttpResponse response = http.send(request);
How can I fix violations?
Create a Named Credential: In Setup, navigate to Named Credentials and create a new credential with the endpoint URL and authentication details.
Update code: Replace hardcoded URLs with
callout:NamedCredentialName/path.Remove credential handling: Let the Named Credential handle authentication headers.
When should I disable this rule?
You may dismiss specific violations for:
Public APIs that require no authentication
Integration tests using mock endpoints
Resources
