authentication_error
Your API key is invalid, missing, malformed, or revoked. This is a configuration error — retry won't help. Check your key and headers first.
What the error looks like
{
"type": "error",
"error": {
"type": "authentication_error",
"message": "invalid x-api-key"
}
}
Diagnostic checklist
- Key starts with
sk-ant-api03-(notBearer, not empty) - Header name is
x-api-key(NOTAuthorization) - No trailing spaces, newlines, or quotes around the key value
- Key belongs to the correct Anthropic workspace
- Key hasn't been revoked in console.anthropic.com/account/keys
- Environment variable is loaded (run
echo $ANTHROPIC_API_KEY)
Correct header format (raw HTTP)
POST /v1/messages HTTP/1.1
Host: api.anthropic.com
x-api-key: sk-ant-api03-YOUR_KEY_HERE
anthropic-version: 2023-06-01
Content-Type: application/json
{...}
Do NOT use
Authorization: Bearer sk-ant-... — that's OpenAI's format. Anthropic uses x-api-key.SDK setup (Python)
import anthropic
import os
# Option 1: Set env var, SDK picks it up automatically
# export ANTHROPIC_API_KEY=sk-ant-api03-...
client = anthropic.Anthropic()
# Option 2: Explicit (avoid hardcoding in source)
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
# Verify key loads:
import os
key = os.environ.get("ANTHROPIC_API_KEY", "")
print(f"Key starts with: {key[:15]}...") # should be sk-ant-api03-
print(f"Key length: {len(key)}") # typically 108 chars
SDK setup (TypeScript)
import Anthropic from "@anthropic-ai/sdk";
// SDK reads ANTHROPIC_API_KEY from env automatically
const client = new Anthropic();
// Or explicit:
const client2 = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY, // never hardcode!
});
// Verify:
console.log("Key prefix:", process.env.ANTHROPIC_API_KEY?.slice(0, 15));
FAQ
I copy-pasted the key exactly — why does it still fail?
Check for invisible characters or trailing newlines. Run
echo -n "$ANTHROPIC_API_KEY" | wc -c — a valid key is ~108 characters. Also check for a leading/trailing space added by your editor.Does the key expire automatically?
No — Anthropic API keys don't expire unless you manually revoke them or your account is suspended. Check the Console to confirm the key is active.
I'm using a .env file but still get 401?
Make sure you're loading the .env file (
from dotenv import load_dotenv; load_dotenv() in Python). Verify the variable name matches exactly: ANTHROPIC_API_KEY.