OpenAI 401 incorrect_api_key
What you see when this happens
- 401 with `code: 'invalid_api_key'` and message 'Incorrect API key provided'
- Immediate failure — no partial success
- Same code worked yesterday, fails today (key rotated)
- Works with a different key, fails with this one
Common causes
Someone with admin access revoked the key.
New key was created; old key is still in your deployment config.
You have keys from multiple OpenAI accounts and grabbed the wrong one.
Key corrupted during copy-paste, storage, or transmission.
How to fix it
Verify key exists in current OpenAI account
Log in to platform.openai.com/api-keys and check if your key ID is in the list of active keys. If not, it was deleted.
Generate a new key and update deployments
Create a new key at platform.openai.com/api-keys and update all deployments simultaneously using your secret manager.
Check for encoding issues in transit
If key is stored in env vars or secret store, verify no encoding issues.
# Check for suspicious characters
key = os.environ["OPENAI_API_KEY"]
suspicious = [c for c in key if not c.isascii() or c.isspace()]
if suspicious:
print(f"Key contains suspicious characters: {suspicious}")
How to prevent it
- Use secret managers with rotation-aware key fetching
- Set up runbook for emergency key rotation
- Never store keys in code, config files, or shell history
- Rotate on a schedule, not just after incidents
Related errors
Deeper reading
Frequently asked questions
How do I know if my key was deleted vs. just wrong?
Check platform.openai.com/api-keys — if your key ID isn't in the list, it was deleted. If it is in the list but you're still getting 401, the key value has been corrupted somehow.
Can I recover a deleted key?
No — deletion is permanent. Create a new key. This is by design for security.