Fix Claude API Error 401 -- Authentication Failed
TL;DR: A 401 error means your API key is missing, invalid, or expired. Verify your key, check environment variables, and ensure the correct header format.
The Problem
When calling the Claude API, you receive an HTTP 401 response:
{
"type": "error",
"error": {
"type": "authentication_error",
"message": "Invalid API key"
}
}
Why This Happens
The Anthropic API requires a valid API key in the x-api-key header. A 401 occurs when:
- The API key is missing from the request headers
- The key has been revoked or rotated in the Anthropic Console
- Environment variables (
ANTHROPIC_API_KEY) are not set or contain whitespace/newlines - You are using the wrong header name (e.g.,
Authorization: Bearerinstead ofx-api-key)
The Fix
Step 1: Verify Your API Key
# Check if the environment variable is set
echo "Key length: ${#ANTHROPIC_API_KEY}"
echo "Key prefix: ${ANTHROPIC_API_KEY:0:10}..."
# Key should start with "sk-ant-" and be ~100+ characters
Step 2: Set the API Key Correctly
macOS / Linux (bash/zsh):
export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"
source ~/.zshrc
In code (Python SDK):
import anthropic
# SDK reads ANTHROPIC_API_KEY automatically
client = anthropic.Anthropic()
Step 3: Verify the Header Format
If making raw HTTP requests, use x-api-key (not Authorization):
# Correct
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model":"claude-sonnet-4-5-20250514","max_tokens":128,"messages":[{"role":"user","content":"Hi"}]}'
Common Variations
| Scenario | Cause | Quick Fix |
|---|---|---|
| 401 in CI/CD pipeline | Secret not injected | Check CI secret configuration |
| 401 after key rotation | Old key cached | Restart application, clear env cache |
| 401 with SDK | ANTHROPIC_API_KEY not exported | Add export before the variable |
| 401 with trailing newline | Copy-paste artifact | Use echo -n when setting key |
Prevention
- Never hardcode API keys: Use environment variables or a secrets manager.
- Rotate keys periodically: Generate new keys in the Anthropic Console and update your environment.
- Test auth separately: Before debugging complex requests, verify auth with a minimal test call.
Paste your error into our Error Diagnostic for an instant fix.
Master Claude Code
Get lifetime access to all ClaudHQ tools, advanced workflows, and production-grade templates.
Get Lifetime AccessWritten by the ClaudHQ team ยท Expert Claude Code guides and tools