AuthenticationError: invalid or missing key
Why this matters
Authentication is the first gate every API call passes through. If your key is wrong, no request reaches OpenAI's servers: understanding this error prevents wasted debugging time and helps you set up credentials correctly from the start.
Explanation
The OpenAI Python SDK requires a valid API key to authenticate every request. When you create a OpenAI() client, it looks for your key in three places in order: the api_key parameter you pass, the OPENAI_API_KEY environment variable, or the ~/.openai/auth.json file (legacy). If none of these exist or the key is invalid, the SDK raises AuthenticationError when you make your first API call.
The error itself doesn't happen at instantiation time: it happens when you call a method like client.chat.completions.create(). The SDK defers authentication validation until the actual request, which means you can create a client object with a bad key without immediately seeing an error. This is important to understand because it means invalid credentials are discovered at request time, not client initialization.
Use this error as a signal to check three things: whether your API key exists in your OpenAI account dashboard, whether you've set the environment variable or passed the key correctly, and whether your key has expired or been revoked. Always treat API keys as secrets: never commit them to version control or share them in logs.
Request code
import os
from openai import OpenAI, AuthenticationError
os.environ['OPENAI_API_KEY'] = 'sk-invalid-key-for-demo'
try:
client = OpenAI()
response = client.chat.completions.create(
model='gpt-4.1',
messages=[
{'role': 'user', 'content': 'Hello'}
]
)
print(response.choices[0].message.content)
except AuthenticationError as e:
print(f'AuthenticationError: {e}') Authentication
To authenticate with OpenAI: (1) Create a free account at platform.openai.com and generate an API key from the dashboard. (2) Set the environment variable: export OPENAI_API_KEY='sk-...' in your shell, or in your .env file if using python-dotenv. (3) The SDK will read this automatically when you call OpenAI(). Alternatively, pass the key directly: OpenAI(api_key='sk-...'). Never hardcode keys in production code.
Response shape
| Field | Description |
|---|---|
error_type | string: always 'authentication_error' for this exception |
message | string: human-readable explanation of why authentication failed |
status_code | integer: typically 401 Unauthorized |
Field guide
message Contains specific reason: 'Invalid API Key provided', 'API key not found', or 'The API key has been revoked'. Read this carefully to diagnose.
status_code 401 means your key is wrong or missing. 403 means your key is valid but your account lacks permissions for that model or feature.
Setup trap
Setting os.environ['OPENAI_API_KEY'] AFTER creating the OpenAI client has no effect. The SDK reads the environment variable at client instantiation time. This is correct behavior, but it catches developers who try to set the key mid-script. Always set or verify your API key before calling OpenAI().
Cost
Attempting API calls with invalid keys still consumes your OpenAI SDK bandwidth and generates error logs, but you are not charged for failed authentication requests. However, if your key is valid but revoked midway through a paid request, you may be partially charged.
Rate limits
Rapid repeated failed authentication attempts (same invalid key, 10+ times per minute) may trigger temporary IP-based rate limiting even before your key is checked. If testing locally with a bad key, use a small delay between attempts.
Common gotcha
The most common mistake is creating the OpenAI client with a bad key and then wondering why your request fails 10 lines later. The error doesn't appear at OpenAI(): it appears at client.chat.completions.create(). Developers often waste time checking their request format when the real problem is the key was never set or was set after the client was instantiated.
Error recovery
AuthenticationErrorTypeError when creating clientRateLimitError immediately after authExperienced dev note
In production, never store API keys in environment variables directly: use a secrets manager and inject them at runtime. More importantly, implement exponential backoff and distinguish between 'bad key' (permanent failure, do not retry) and 'rate limited' (temporary, retry with backoff). A single line: if isinstance(e, AuthenticationError): raise: prevents you from burning through your quota retrying a permanently invalid key.
Check your understanding
If you create an OpenAI client with api_key='sk-invalid', then immediately call client.chat.completions.create(), at what point does AuthenticationError get raised: at client instantiation or at the API call? Why does this matter for error handling?
Show answer hint
The SDK defers authentication until the actual HTTP request is made. This means you need to wrap your API calls in try/except, not just client creation. It also means you can't catch auth errors at startup: they appear only when you first use the client.
openai.api_key = 'sk-...' or openai.ChatCompletion.create(): those are deprecated and have different error handling.