client = OpenAI() raises a 401 error even though I thought I configured my key.
Why this happens
The Python SDK reads OPENAI_API_KEY from the environment unless you pass api_key explicitly. A missing variable, a mistyped/revoked key, or a key belonging to a project without the required access can all produce a 401 response.
Answer 1: Set the environment variable (recommended)
Keep secrets outside the repository. In PowerShell, set it for the current terminal before running the program:
$env:OPENAI_API_KEY = "your_api_key_here"
python app.py
Then create the client normally:
from openai import OpenAI
client = OpenAI()
For a persistent development-machine setting, use your operating system’s environment-variable UI or a secret manager. Restart the terminal after changing a persistent variable.
