Build HTTP Headers for an AI API Request
Every AI API request requires a specific set of HTTP headers: an Authorization header with the correct format for the provider, Content-Type set to application/json, and in some cases provider-specific headers like Anthropic's anthropic-version or OpenAI's OpenAI-Organization for team accounts. Getting headers wrong is one of the most common causes of 401 Unauthorized and 400 Bad Request errors when first integrating an AI API. The headers builder generates the complete header set for a given provider, with placeholders for your API key and optional fields clearly labelled. The Authorization header format differs by provider: OpenAI uses "Authorization: Bearer sk-..." while Anthropic uses "x-api-key: sk-ant-..." as a custom header rather than the standard Authorization header. Gemini uses an API key as a query parameter (key=...) rather than a header at all for REST requests, though the Python and JS SDKs handle this automatically. These differences trip up developers building provider-agnostic clients or switching between providers. This example generates headers for an Anthropic Claude API request, including the required anthropic-version header that specifies the API version date. Missing this header returns a 400 error with a message about the version being required — a confusing error for developers new to the Anthropic API who expect only an API key to be necessary.
Provider: Anthropic API Key: sk-ant-api03-YOUR_KEY_HERE Model: claude-3-5-sonnet-20241022 Stream: true Beta features: tools, prompt-caching
FAQ
- Why does Anthropic use x-api-key instead of Authorization?
- Anthropic chose a custom header name for API key authentication. Both approaches are functionally equivalent from a security standpoint. The key difference is that standard HTTP middleware like API gateways may handle Authorization headers differently, so be aware when routing through a proxy.
- What is the anthropic-version header?
- The anthropic-version header pins your requests to a specific version of the Anthropic API, ensuring behaviour does not change when Anthropic releases API updates. The recommended value is "2023-06-01". Omitting this header causes a 400 error.
- Do I need special headers to enable prompt caching on Claude?
- Yes. Prompt caching is currently a beta feature on Anthropic and requires adding anthropic-beta: prompt-caching-2024-07-31 to your request headers. Without this header, cache_control markers in your messages are ignored.
Related Examples
A well-structured system prompt is the single biggest lever for improving LLM ou...
Design an LLM Processing ChainLLM chains connect multiple model calls in sequence, where the output of one ste...
Build an OpenAI Chat Completion RequestThe Chat Completion API is the primary interface for all GPT models and the foun...
Build an Anthropic Messages API RequestThe Anthropic Messages API is the primary interface for all Claude models. Unlik...