How to Fix “Incorrect API key provided” (401 invalid_api_key) on the OpenAI API
The key is almost always right. What's wrong is which key arrived, and a trailing newline is the single most common culprit.
On this page
It runs on your machine. It fails the moment it's anywhere else:
openai.AuthenticationError: Error code: 401 - {'error': {'message':
'Incorrect API key provided: sk-proj-...abcd', 'type': 'invalid_request_error',
'code': 'invalid_api_key'}}
You check the key. It's correct. You paste it again, carefully this time, and get the same error back. At this point most people regenerate the key, which changes nothing and costs them the 10 minutes it takes to update every place the old one was stored.
The key usually isn't the problem. What reached the API is, and those are different questions.
#The 6 causes, in the order they happen
| # | Cause | Tell | Time to check |
|---|---|---|---|
| 1 | Trailing whitespace or newline | Length is 1–2 too long | 1 min |
| 2 | The variable never loaded | Length is 0 | 1 min |
| 3 | A different key shadowing yours | Tail doesn't match | 3 min |
| 4 | Key revoked or rotated | Tail matches, still 401 | 2 min |
| 5 | Wrong organisation header | Works on a different account | 5 min |
| 6 | Key pasted into the wrong field | Message quotes a partial key | 2 min |
#1. Print what actually arrived
Do this before anything else. It splits the problem in half:
import os
k = os.environ.get("OPENAI_API_KEY", "")
print(repr(len(k)), repr(k[-6:]) if k else "MISSING")
repr is the point. A plain print hides a trailing newline and you'll stare straight past it.
- Length 0 — the variable never loaded. Go to 2.
- Length a character or 2 longer than the dashboard shows — whitespace. Strip it.
- Tail doesn't match — something else is supplying the key. Go to 3.
- Both match exactly — the key itself is being rejected. Go to 4.
Never log the whole key. A key in a log file is a key in everyone's log aggregator.
#2. The newline nobody sees
This is the single most common cause I run into, and what makes it expensive is that it's invisible in every editor you'd use to check. The value looks right, the dashboard says it's right, and the two genuinely are identical apart from 1 character that doesn't render.
# both of these leave a newline on the value
OPENAI_API_KEY="sk-proj-abc...
"
export OPENAI_API_KEY=$(cat key.txt)
cat faithfully keeps the file's final newline, which almost every editor adds for you on save, and the Authorization header then goes out with a line break embedded in it. The API sees a key that doesn't match anything, so it tells you the key is incorrect — which is true, just not in the way you'd assume.
export OPENAI_API_KEY=$(tr -d '\n' < key.txt)
In application code, strip defensively at the boundary:
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"].strip())
That 1 call has saved me more time than any other line in this guide.
#3. Something else is supplying the key
If the tail doesn't match what you expect, the value is coming from somewhere you forgot. Check in this order, because that's roughly how often each one is to blame:
- A real environment variable beating your
.env. Most loaders won't overwrite a variable that's already set. Oneexportin your shell profile from months ago wins silently, forever. - The wrong
.envfile. Running from a parent directory, or a.env.localthat takes precedence. - A baked container image. A build-time
ENVis frozen into the image. Rebuilding is the only way to change it. - CI secrets. A repository secret and an organisation secret with the same name resolve by precedence, not by what you edited last.
Check what the shell is holding:
env | grep -c OPENAI_API_KEY
Anything other than 0 or 1 means you have a collision.
#4. The key is real but rejected
If the length and tail both match, the key is being refused rather than mangled. Three reasons:
It was revoked. Deleting a key in the dashboard takes effect immediately. Anything still holding it gets a 401 on the next call.
It belongs to a deleted project. Removing a project invalidates the keys scoped to it, and the error you get back says nothing about the project.
It leaked and was auto-revoked. Keys pushed to a public repository are detected and disabled, usually within minutes. If you committed one, assume it's dead and rotate — don't try to un-revoke it.
#5. Right key, wrong organisation
If you belong to more than 1 organisation, a stale OPENAI_ORG_ID sends an otherwise valid key to an account it has no membership in. The result is a 401 that looks exactly like a bad key.
env | grep OPENAI_ORG
If that returns something you don't recognise, unset it and try again. Most setups don't need it at all.
#6. Rotate without causing the next outage
Once you've found the cause, the fix is usually a new key — and that's where people create a second incident on top of the first. A key is almost never stored in 1 place by the time a project is a few months old.
Write the list down before you start: your local .env, the CI secret, the deployment environment, any container image that baked it in, the queue worker that runs separately from the web process, and whatever a colleague has on their laptop. Create the new key, update every one of those, confirm traffic is flowing on the new key, and only then revoke the old one. Revoking first turns a controlled change into an outage, and it's the single most common way a routine rotation goes wrong.
#Match your symptom to the fix
| What you're seeing | Likely cause | Go to |
|---|---|---|
| Works locally, 401 in Docker or CI | Different key, or a baked image | 3 |
| Length is 1 longer than the dashboard | Trailing newline | 2 |
| Started failing with no deploy | Key revoked or rotated | 4 |
| Error quotes a key you don't recognise | Shadowing variable | 3 |
| Same key works for a colleague | Organisation mismatch | 5 |
| Length is 0 | Variable never loaded | 1 |
#When it's still 401
Generate a brand new key, put it directly in a single-file script with no .env involved, and call the API with it. Two outcomes, and both are useful.
It works. The key was never the problem — your configuration loading is. You now know where to look.
It still fails. The account itself is in a state you can't see. Open a ticket with the request id from the response header and the last 6 characters of the key.
Worth noting: a 401 and a quota failure are completely different problems that both arrive at deploy time. If the code in the body says insufficient_quota rather than invalid_api_key, you want the quota guide instead. And if the key is fine but the model name is rejected, that's a model access problem.
Frequently asked questions
Can I tell a bad key from a revoked one by the error?
No. Both return 401 with code invalid_api_key, and the message quotes a masked version of whatever you sent. The masked tail is the useful part — it tells you which key arrived, not whether it's still valid.
Why does the error show part of my key?
So you can identify which key was used without exposing it. Compare that tail against your dashboard. It's the fastest way to spot a shadowing variable.
Do project keys and user keys behave differently?
For authentication, no — both return the same 401 when rejected. They differ in what they can reach and which budget they draw on, which shows up as quota and permission errors rather than 401s.
Is it safe to put the key in code for a test?
Only in a file you will delete, never in anything tracked by git. Leaked keys are detected and revoked automatically, which turns a 5-minute test into a rotation.
Written by
Vemuri Abhiram
Founder & Editor
I write every post here. The tools I review are ones I pay for and run on real client work, not demo accounts, and every number you see came off my own invoice or dashboard.
You might also like
How to Fix “You exceeded your current quota” (insufficient_quota) on the OpenAI API
Two different problems return 429 on the OpenAI API. One is worth retrying and one never is. Here's how to tell them apart in 2 minutes.
Vemuri Abhiram6 min read
Claude API Error 529 “overloaded_error”: What It Means and How to Handle It
What a 529 overloaded_error actually means, why retrying is correct for it, and the spend-cap 429 that will break a naive retry loop.
Vemuri Abhiram6 min read
How to Fix “The model does not exist or you do not have access to it” (model_not_found)
A typo and a permissions problem return the identical model_not_found error. List the models your key can actually reach and the ambiguity disappears.
Vemuri Abhiram6 min read
More from Underread, once a week.
The guides worth reading and the tests worth trusting. One email, every Friday.
No spam. Unsubscribe in one click.