ERROR CODES / ENGLISH
401 invalid_api_key: your API key is not accepted
Ranked causes of 401 authentication failures, from a stray space in the key to a disabled key, with a curl check to isolate the client.
Reviewed 2026-11-13 · ERROR CODES / 401 · Chinese detail: 完整中文页
What it means
A 401 means your key was not accepted. Usually it was copied with a space or newline, the variable name is wrong, or the key is from the wrong environment.
Isolate the client with curl: success means a client problem, a 401 means the key or the site.
// OpenAI
{'error': {'message': 'Incorrect API key provided: sk-xxx. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}}
// Anthropic
{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}
// Common relay responses
{"error":{"message":"无效的令牌","type":"new_api_error"}}
{"error":{"message":"令牌已过期","type":"new_api_error"}}
Common causes
| Share | Cause | How to confirm | |
|---|---|---|---|
| 40% | Key copied with a space or newline | `echo "$KEY" \ | cat -A` and inspect both ends |
| 25% | Wrong environment variable name | The client may not read OPENAI_API_KEY | |
| 15% | Wrong key (test vs production) | Compare the first 8 characters in the dashboard | |
| 10% | Key disabled or deleted | Check its status in the dashboard | |
| 10% | Wrong header format | Use Authorization: Bearer sk-xxx or x-api-key: sk-xxx |
How to confirm
Verify with curl:
# OpenAI-compatible
curl https://api.example.com/v1/models \
-H "Authorization: Bearer $KEY"
# Anthropic
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model":"claude-sonnet-5-5","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}'
Success points to the client; a 401 to the key or the site.
A wrong name counts as "no key configured":
| Client | Common variable name |
|---|---|
| OpenAI SDK | OPENAI_API_KEY |
| Anthropic SDK | ANTHROPIC_API_KEY |
| Claude Code | ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY |
| Codex CLI | OPENAI_API_KEY |
| Cursor | Settings UI; not environment variables |
Fix
In order: strip whitespace, correct the variable name, confirm the key matches the site and environment, check it is enabled, and use the documented header format.
If it still fails
| Symptom | Responsible party |
|---|---|
| curl returns 401, a different key works | Your key |
| Same key works on site A, 401 on site B | Site B |
| Worked yesterday, 401 today, key unchanged | The site disabled or expired the key |
| 401 for only one model | That group has not enabled it |
Relay keys and official keys are not interchangeable: an sk-proj- key from OpenAI always returns 401 on a relay.
General guidance, not a statement about any specific provider. For measured data, see the relay directory and method.