How to Fix an OpenAI 401 'Invalid API Key' Error
Track down why the OpenAI API rejects your key and get a valid request flowing again.
A 401 from the OpenAI API almost always means the key your code sent does not match a live key on your account. The fix is rarely the key itself. It is usually a stray space, the wrong environment variable, a project mismatch, or a key that was rotated out. This guide walks through the checks in the order that catches the most cases first.
- An OpenAI account with billing or free credits available
- Access to the platform.openai.com dashboard
- A terminal with curl installed
Step 1: Read the exact error body
The status code alone is not enough. Print the JSON body the API returned. The message field tells you whether the key is missing, malformed, or simply unknown to the server.
Step 2: Confirm the variable is actually set
If the message shows a blank or truncated key, your environment variable never reached the process. Echo it back, then check for hidden whitespace or quotes that crept in from a copied line.
Step 3: Match the key to the right project
Newer keys start with sk-proj- and are scoped to a single project. If the model you call lives in a different project, or your org header points elsewhere, you get a 401 even with a real key. Set the project explicitly so there is no ambiguity.
OPENAI_API_KEY=sk-proj-your-real-key
OPENAI_PROJECT_ID=proj_abc123
OPENAI_ORG_ID=org_xyz789Step 4: Rotate the key if it was ever exposed
If the key was committed to git, pasted in a chat, or printed in logs, OpenAI may auto-revoke it. Create a fresh secret key, paste it into your secret store, and delete the old one. Never paste a key back into the dashboard search box to test it.
Result
After setting a clean key in the right project, the same curl call returns a 200 with a list of models. In one common case a developer had OPENAI_API_KEY set in their shell but their app loaded a stale .env file, so the process saw an old revoked key. Removing the .env line and relying on the shell variable fixed it in under a minute.
Watch related tutorials
12:38
14:09
17:53
15:00
12:00
1:42:18