I once found a single error line waiting for me in the morning, left behind by a scheduled job that had run overnight behind one of my apps: "401 Invalid API Key." It had worked the night before, and I hadn't changed anything.
My first move was to assume the key had broken, so I generated a new one in the Console. That went nowhere. The same 401 came back with the new key. The real cause was that the environment variable I'd set in my shell was never passed to the process that launched the job.
A 401 only tells you the key wasn't accepted. It doesn't promise the key is wrong, and more often than not the cause sits outside the key itself. Here is the order I follow now.
First, Confirm It Really Is a 401
What I'd say first is: don't mix up error types. It's easy to keep blaming the key while a different error is the one in front of you.
{
"type": "error",
"error": {
"type": "authentication_error",
"message": "Invalid API Key"
}
}If you see authentication_error, this article applies. For lookalikes, here is where I look:
| Symptom | Where to look |
|---|---|
| 401 authentication_error | Key, headers, how you authenticate (this article) |
| 403 permission_error | Key permissions, organization or workspace, region |
| 400 with "credit balance is too low" | Prepaid credit balance (billing error guide) |
| 429 rate_limit_error | Request rate and limits (error handling) |
A low balance comes back in a different shape, not as a 401. I once spent hours poking at authentication because I assumed "out of credit" meant "401." I'd rather you skip that detour.
Cause 1: The Environment Variable Is Missing or Never Read
The most common cause is an empty ANTHROPIC_API_KEY, or one your program can't see. Start by checking the terminal you're using:
# Show only the first 10 characters (never print the whole key)
echo "${ANTHROPIC_API_KEY:0:10}..."
# Empty means unset. If it doesn't start with sk-ant-, the value is offSeeing a value here is not the end of it. The value your terminal sees and the value your program sees can be different things. That was exactly my overnight job.
- Jobs started by cron, launchd, or systemd don't read
~/.zshrc - Processes launched from an IDE or a GUI app may not inherit your terminal's
export - Docker and serverless environments only see what you pass in explicitly
# macOS / Linux: add to your shell config
echo 'export ANTHROPIC_API_KEY="sk-ant-api03-xxxxx..."' >> ~/.zshrc
source ~/.zshrc
# Windows (PowerShell): set as a user variable (restart PowerShell afterward)
[System.Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "sk-ant-api03-xxxxx...", "User")If you use a .env file, check where it lives and whether the loading code actually runs:
import os
from dotenv import load_dotenv
load_dotenv() # Loads .env (relative to the current working directory)
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
raise ValueError("ANTHROPIC_API_KEY is not set")
print(f"API Key found: {api_key[:10]}...")Check from inside the program. I stopped trusting an echo in my terminal and started printing the value from the process that makes the call. That one rule ended my late nights over environment variables.
Cause 2: Whitespace, Newlines, or Quotes in the Key
This is the most frustrating one, because you can't see it. A copied key may carry a trailing newline or space, or a .env entry may be read with its quotation marks as part of the value.
# Reveal invisible characters around the key
printf '%s' "$ANTHROPIC_API_KEY" | od -c | tail -3
# Inspect the .env line (look for quotes or trailing spaces)
grep ANTHROPIC_API_KEY .env | cat -AIn the cat -A output, the line should end right before the $. Whether quotes are stripped depends on the tool reading the file: source in a shell and an app's own loader can behave differently. When in doubt, try it once without quotes.
Cause 3: The Key Was Revoked, or Belongs to Another Organization
If you delete or regenerate a key in the Anthropic Console, the old one stops working immediately. On a team, someone tidying up can remove a key others rely on.
Three things to check:
- The key still appears in the Console's API Keys list
- Its status shows as active
- The organization or workspace that issued it is the one you mean to use
When I kept separate keys for testing and production, I once pasted a key from one organization into the other's config. The string was correct, and it was still rejected.
A key pasted into a public repository or a shared space may also have been disabled. If that could apply to you, issue a new one and track down every place the old one lives.
# Send a minimal request with the new key and look only at validity
curl -s https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-sonnet-4-6",
"max_tokens": 20,
"messages": [{"role": "user", "content": "Hello"}]
}' | head -c 300A response starting with {"id":"msg_... means the key is valid. Don't forget your .env, CI secrets, and deployment settings.
Cause 4: The Header Format Is Wrong
The Claude API takes the key in an x-api-key header, not in Authorization: Bearer. It's the spot where people coming from other providers trip most often.
import anthropic
# The official SDK sets the x-api-key header for you
client = anthropic.Anthropic() # Reads ANTHROPIC_API_KEY from the environment
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}],
)
print(message.content[0].text)If you call over plain HTTP without the SDK, send all three headers:
-H "x-api-key: YOUR_API_KEY"
-H "anthropic-version: 2023-06-01"
-H "content-type: application/json"If a gateway or internal proxy sits in between, also check that ANTHROPIC_BASE_URL points where you intend. If it points at a gateway, you need the key that gateway expects. The question is whether you're sending an Anthropic key to some other service's endpoint.
Cause 5: "401 Invalid bearer token" in Claude Code
Claude Code authenticates either through browser login (OAuth) or an API key. Sometimes the login appears to succeed and the next run still returns 401.
API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid bearer token"}}
Before suspecting a corrupted token, I check whether two authentication paths are fighting. A leftover API key in the environment can take priority over your login.
# Check for a leftover key in the environment (values hidden)
env | grep -i anthropic | sed 's/=.*/=(set)/'If an old key is there, remove it and restart Claude Code. For how to tell which path is active, see the one line I checked first when Pro was paid but the Console showed charges (Japanese).
If it still fails, run /logout inside Claude Code, then /login again. Updating Claude Code before you retry is worth doing too.
# How you update depends on how you installed it; check the version first
claude --version
claude updateDeleting credential files by hand is my last resort, since storage locations differ between environments. /logout and /login are enough in most cases.
Cause 6: Proxy, VPN, or Firewall Interference
On some corporate networks and VPN setups, requests are rewritten along the way and the auth header never arrives. If it only fails through the proxy, suspect this.
# Check proxy settings
echo "HTTPS_PROXY: $HTTPS_PROXY"
echo "NO_PROXY: $NO_PROXY"
# Send the same request without the proxy and compare results
curl -s --noproxy '*' 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-6","max_tokens":10,"messages":[{"role":"user","content":"Hi"}]}' \
-o /dev/null -w "%{http_code}\n"If you only get 200 without the proxy, add api.anthropic.com to the allowlist or bypass list. For a VPN, turning it off briefly is the fastest way to isolate it.
Confirm the Fix With One Call
After changing anything, verify authentication with the smallest possible request:
import sys
import anthropic
def verify_authentication() -> bool:
try:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=20,
messages=[{"role": "user", "content": "Say OK"}],
)
print("Authenticated:", response.content[0].text)
return True
except anthropic.AuthenticationError as e:
print("Authentication error (401):", e)
return False
except anthropic.APIConnectionError as e:
print("Connection error:", e)
return False
if __name__ == "__main__":
sys.exit(0 if verify_authentication() else 1)Catching AuthenticationError and APIConnectionError separately keeps a 401 from being confused with a request that never arrived.
What I Do to Keep It From Coming Back
Keys stay out of code. They live in environment variables or a secrets manager (a cloud provider's, or a password manager). On a team, I'd split keys by person and by purpose, so one person's cleanup doesn't break everyone else.
I also decide in advance how to handle a 401. Resending with the same key won't change the answer.
import anthropic
def call_once_then_stop(client: anthropic.Anthropic, **kwargs):
"""Don't retry a 401; stop and move on to finding the cause."""
try:
return client.messages.create(**kwargs)
except anthropic.AuthenticationError:
# Retrying the same key is pointless. Log it and let a person check.
raiseBefore retrying a 401, remove one cause. Interval-based retries suit 429 and 5xx errors, but they don't suit authentication failures.
The Order, Once More
When I get a 401, I check in this order: that it really is a 401, the environment variable as seen from inside the program, whitespace in the key, revocation and organization, headers and endpoint, the login path if it's Claude Code, and finally the proxy.
If you're stuck right now, start by printing the first ten characters of the key from inside the program that makes the call. That is where I began, and it solved mine.
For related reading, see Claude API Error Handling and Retry Strategies and the First API Call Troubleshooting FAQ.