Blog

OpenAI API 401 "Incorrect API key provided" (invalid_api_key): How to Fix It

Short answer

A 401 with Incorrect API key provided and "code": "invalid_api_key" means OpenAI didn't accept the key in your request's Authorization header. OpenAI's error code guide lists four causes:

  • a typo or an extra space in the key
  • a key that belongs to a different organization or project
  • a key that has been deleted or deactivated
  • an old, revoked key that is still cached locally

Public bug reports add two more: a placeholder sent in place of the key (undefined, dummy_key), and a key for another service, such as an API gateway, sent to api.openai.com.

The error message helps you narrow it down. It shows the first and last characters of the key that was sent, and some clients, Codex among them, also print the URL. Compare both with what you meant to send, then fix that value or create a new key. Retrying the same request won't help.

What the error looks like

The OpenAI Python SDK raises AuthenticationError. This example is from openai/openai-python#1968:

text
AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-qVL45***************************************D1Vi. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}

Codex prints the same message with the URL it called. This one comes from farion1231/cc-switch#6812, shortened. The user had Codex set up with a third-party relay, but the request went to OpenAI:

text
unexpected status 401 Unauthorized: Incorrect API key provided: sk-cab2f****3e8b. You can find your API key at https://platform.openai.com/account/api-keys., url: https://api.openai.com/v1/responses, ... auth error code: invalid_api_key

When a placeholder is sent, the message shows it in place of the masked key:

text
Incorrect API key provided: undefined.
Incorrect API key provided: dummy_key

These come from anse-app/chatgpt-demo#297, where the app was deployed without the key set, and The-PR-Agent/pr-agent#4195, where the GitHub Action ran without its OpenAI key secret.

Other 401 errors from OpenAI

The error code guide lists several 401s. Check which message you got before you replace the key:

Message Cause Fix
Incorrect API key provided The key isn't correct Fix the value, or generate a new key
Invalid Authentication The key or the requesting organization is wrong. The guide also mentions revoked keys and keys without permission for the endpoint Check the key and organization ID you send
You must be a member of an organization to use the API Your account isn't in an organization Ask an organization owner to invite you, or contact OpenAI
IP not authorized The request IP isn't on the project's or organization's IP allowlist Send from an allowed IP, or update the allowlist

Why it happens

The value is malformed. A key copied with a missing character, a line break or a space fails. This often happens when a key is pasted from a chat message, a PDF or a terminal that wrapped the line.

A stale key wins. The OpenAI Python SDK reads OPENAI_API_KEY from the environment when you don't pass api_key. An old export in ~/.zshrc or ~/.bashrc, or a CI secret that was never updated, keeps sending a revoked key. python-dotenv's load_dotenv() doesn't override environment variables that are already set, so a new value in .env loses to an old one in your shell.

A placeholder is sent. If the variable your code reads is empty or misnamed, some apps send a literal such as undefined or a dummy value. In pr-agent#4195, most of the failed runs passed an empty key variable, for example on Dependabot and fork pull requests, which get no Actions secrets. The action then sent its placeholder key.

The key went to the wrong host. A key issued by a gateway or relay only works there. If the base URL isn't applied, the client falls back to api.openai.com, and OpenAI rejects the key. In cc-switch#6812, this happened after a Codex update when an old conversation was continued. New conversations worked.

The key belongs elsewhere or was deleted. A key from another organization or project, or one that was deleted or deactivated, fails the same way.

How to fix it

  1. Read the masked key in the error. Compare its first and last characters with the key you meant to use. If they don't match, find where the other value comes from. If you see undefined, an empty value or a dummy, the variable wasn't set.
  2. Check the URL. If the error shows api.openai.com but you meant to use a gateway, fix the base URL setting, not the key.
  3. List what's set. Run env | grep OPENAI (PowerShell: Get-ChildItem Env:OPENAI*) in the shell that starts your app. Check shell profiles, .env files, IDE run configurations and CI secrets for old values.
  4. Test the key on its own:
bash
curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"

A model list means the key works and the problem is in how your app loads it. A 401 here means the key itself is wrong.

  1. Generate a new key if you're unsure. Create one on the API keys page, replace the old value everywhere it's stored, and delete the old key.
  2. For Invalid Authentication, check the organization and project. The Python SDK also reads OPENAI_ORG_ID and OPENAI_PROJECT_ID. If one of them points to an organization or project the key doesn't belong to, unset it or correct it.

If you use Codex

  • With a custom provider, Codex reads the key from the environment variable named by env_key in ~/.codex/config.toml. Set it in the shell that starts Codex, and restart Codex after you change it.
  • Check that model_provider and the provider's base_url are set in the config Codex actually loads. If the error shows url: https://api.openai.com/..., the request didn't use your provider.
  • If you signed in to Codex with an OpenAI API key, that key is billed through your OpenAI Platform account. Sign in again with a valid key.
  • openai/codex#48359 reports this 401 from Codex's automatic approval review on 0.153.4 with ChatGPT sign-in rather than an API key. If that matches your setup, update Codex and add details to that issue.

Using a TeamoRouter key

TeamoRouter is an API gateway with one key for GPT, Claude, Gemini and DeepSeek. It's OpenAI-compatible: /v1/chat/completions and /v1/responses work with the official SDKs. A TeamoRouter key starts with sk-teamo- and is sent the same way, as Authorization: Bearer. Sent to api.openai.com, it gets exactly this 401, so set the base URL wherever you use it. There's no subscription; you pay per use.

  1. Create an API key in the TeamoRouter console.
  2. Top up from $5. The top-up dialog takes cards. You can also click Pay with crypto and pay with USDT, USDC or ETH from any exchange app — the checkout shows which networks your amount supports (BEP20 works from $5). Step by step: Pay with USDT.
  3. Test the key:
bash
curl https://api.teamorouter.com/v1/models \
  -H "Authorization: Bearer sk-teamo-..."
  1. Set the base URL and key in your code:
python
from openai import OpenAI

client = OpenAI(
    api_key="sk-teamo-...",
    base_url="https://api.teamorouter.com/v1",
)

resp = client.responses.create(model="gpt-6-sol", input="Hello")
print(resp.output_text)

For Codex, add a provider to ~/.codex/config.toml:

toml
model_provider = "teamorouter"
model = "gpt-6-sol"

[model_providers.teamorouter]
name = "TeamoRouter"
base_url = "https://api.teamorouter.com/v1"
env_key = "OPENAI_API_KEY"
wire_api = "responses"

Then set OPENAI_API_KEY to your TeamoRouter key and start codex from that shell. GET /v1/models lists the model IDs you can use. Windows commands are in Install and connect Codex, and the other protocols are in the API integration guide.

FAQ

Is this a rate limit or billing problem? No. Those are 429 errors with their own codes, such as credit_balance_exhausted. A 401 is about the key itself.

I just created the key. Why is it rejected? Check for a copy error first, then check that your app isn't still reading an older value from the environment. Test the new key with curl to rule out the app.

Does a ChatGPT Plus or Pro subscription give me an API key? No. API keys come from the OpenAI Platform, and API usage is billed there, separately from ChatGPT plans.

Can I reuse an OpenAI key with another provider? No. Each provider or gateway only accepts keys it issued. Use the key from the service your base URL points to.

Next steps

Ready to connect?Log in · top up · create an API key — three steps to start.