How do developers configure and utilize custom HTTP headers during programmatic Apex REST callouts?
Answer
Basics: HTTP headers carry metadata separate from the body: what format you send (Content-Type), what you accept (Accept), authentication (Authorization), and custom tracking (X-Correlation-Id). In Apex callouts you build an HttpRequest, set headers, send it with Http.send, and read response headers if needed.
How it works:
- Create
HttpRequest, set endpoint and method. req.setHeader('Content-Type', 'application/json');andreq.setHeader('Accept', 'application/json');- Add custom headers:
req.setHeader('X-Correlation-Id', UUID.randomUUID().toString()); - For authentication use a Named Credential (
callout:Name/...) so theAuthorizationheader is added by the platform; for API-key APIs put the key in a credential parameter rather than code. - Send, then read
res.getHeader('Retry-After')orres.getHeaderKeys().
Advanced / deep dive: Useful headers: Idempotency-Key for safe retries, If-Match/ETag for optimistic concurrency, Accept-Encoding with req.setCompressed(true) for compressed request bodies, X-Request-Id for tracing across systems. In the External Credential model, header values can use credential parameter formulas (for example {!$Credential.ERP_Auth.ApiKey}) so secrets are never in Apex. Header names are case-insensitive. Setting the same header twice overwrites it. Some headers are controlled by the platform and cannot be set arbitrarily (verify restrictions in current docs). Set explicitly (maximum 120,000 ms) so slow services do not eat the cumulative callout time. Avoid logging headers that contain secrets.