Critical severity HTTP 401 beginner · Fix: 2-5 min

AuthenticationError

openai.AuthenticationError (HTTP 401)

What this error means
The OpenAI Assistants API rejected your request due to an invalid or missing API key, blocking authentication.

Stack trace

traceback
openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Invalid API key provided', 'type': 'authentication_error', 'param': null, 'code': 'invalid_api_key'}}
QUICK FIX
Set your valid OpenAI API key in the environment variable OPENAI_API_KEY before running your code.

Why it happens

This error occurs when the API key used in the OpenAI Assistants client is missing, malformed, expired, or revoked. The server rejects the request because it cannot authenticate the client without a valid key.

Detection

Check for openai.AuthenticationError exceptions in your API calls and verify the API key environment variable is set and correctly loaded before making requests.

Causes & fixes

1

API key environment variable is not set or misspelled

✓ Fix

Ensure the environment variable (e.g., OPENAI_API_KEY) is set correctly in your environment and matches the variable your code reads.

2

Using an expired or revoked API key

✓ Fix

Generate a new API key from the OpenAI dashboard and update your environment variable accordingly.

3

Passing the API key incorrectly in the client initialization

✓ Fix

Use the OpenAI SDK v1+ pattern with os.environ to load the key and pass it properly to the client constructor.

Code: broken vs fixed

Broken - triggers the error
python
from openai import OpenAI
client = OpenAI(api_key="wrong_or_missing_key")  # This causes AuthenticationError
response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}])
print(response)
Fixed - works correctly
python
import os
from openai import OpenAI
os.environ["OPENAI_API_KEY"] = "your_valid_api_key_here"  # Set your valid API key here
client = OpenAI()
response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}])
print(response)  # Works without AuthenticationError
Removed hardcoded or missing API key and instead set the valid key in the environment variable OPENAI_API_KEY, allowing the OpenAI client to authenticate properly.

Workaround

If you cannot update the environment immediately, catch AuthenticationError exceptions and prompt for manual API key input or fallback to cached valid credentials.

Prevention

Use environment variables to manage API keys securely and validate their presence at application startup to avoid runtime authentication failures.

Python 3.9+ · openai >=1.0.0 · tested on 1.x
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.