API key security: what not to do
Why this matters
A leaked API key gives anyone access to your OpenAI account, burning your credits and potentially exposing conversation data. This is the single most common cause of account compromise for developers.
Explanation
The OpenAI SDK reads your API key from three sources: (1) the api_key parameter passed to OpenAI(), (2) the OPENAI_API_KEY environment variable, or (3) from a .env file if you use python-dotenv. The only safe approach is option 2 or 3: never option 1 with a literal string in your code.
When you hardcode a key like OpenAI(api_key="sk-proj-...") in your source file, you risk accidentally committing it to GitHub, uploading it to a public repository, or sharing it in a screenshot. Git history is permanent: even if you delete the file, the key stays in the commit log forever. Automated bots scan public repos for leaked keys and drain accounts within minutes.
Use os.getenv('OPENAI_API_KEY') or python-dotenv to load the key at runtime. For production, store the key in a secrets manager (AWS Secrets Manager, HashiCorp Vault, GitHub Secrets for CI/CD). The OpenAI SDK will automatically pick up OPENAI_API_KEY from your environment: you don't even need to pass it explicitly.
Request code
import os
from openai import OpenAI
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[
{'role': 'user', 'content': 'Say hello.'}
]
)
print(response.choices[0].message.content) Authentication
1. Create an API key at https://platform.openai.com/account/api-keys 2. On your local machine, set the environment variable: `export OPENAI_API_KEY='sk-proj-...'` (macOS/Linux) or `set OPENAI_API_KEY=sk-proj-...` (Windows) 3. Verify it works: `python -c "from openai import OpenAI; print(OpenAI().models.list())"` 4. Never add your key to .env, .env.local, or any file tracked by git. Add `.env` to `.gitignore`. 5. For deployed apps, inject the key via environment variables set by your hosting platform (Railway, Render, AWS Lambda environment variables, etc.).
Response shape
| Field | Description |
|---|---|
choices | [List of completion objects] |
choices[0].message.content | The generated text response |
choices[0].finish_reason | Reason completion ended (e.g., 'stop') |
usage.prompt_tokens | Number of input tokens |
usage.completion_tokens | Number of output tokens |
model | The model used (e.g., 'gpt-4o-mini') |
Field guide
choices[0].message.content The actual LLM output: this is what you extract and use in your application
usage A hidden field many developers ignore. Track prompt and completion tokens here to monitor costs and detect runaway API calls early
Setup trap
You must set the environment variable *before* your Python process starts, not after importing OpenAI. If you do `import os; os.environ['OPENAI_API_KEY'] = 'sk-proj-...'` inside your Python script, this technically works because the OpenAI() constructor reads the environment at instantiation time: but this is exactly the anti-pattern to avoid. Never put the literal key in Python code at all, even in environment variable assignments.
Cost
A leaked key typically results in $1,000–$10,000 in fraudulent API charges within hours. The sooner you rotate a leaked key (via https://platform.openai.com/account/api-keys), the sooner you stop the bleeding. You cannot undo charges: OpenAI will not refund them.
Rate limits
Not applicable: rate limits are per-key usage, not per authentication method.
Common gotcha
Developers often think 'I'll just check that key and delete it after testing': but if they push to GitHub first, the key is already compromised. Every commit is scanned by automated key-stealing bots within seconds of being public. Even deleting it later doesn't matter because the history is permanent.
Error recovery
AuthenticationErrorPermissionError or 401Experienced dev note
Rotate your API keys regularly: not just when leaked. Set a calendar reminder to regenerate keys every 90 days. For team environments, use separate keys for each environment (dev, staging, prod) and each developer. If a dev laptop is stolen, you only rotate that one key, not all of them. Also: store your `.env` file locally with restrictive file permissions (`chmod 600 .env`), and use a `.env.example` file committed to git showing the structure without the actual values: this lets teammates know what variables they need to set.
Check your understanding
Your GitHub repo is public, and you just noticed a hardcoded OpenAI API key in a commit from 3 days ago that you pushed. The key is still in the repo but you deleted it in the latest commit. Why is deleting it not enough to secure your account, and what's the single action you should take right now?
Show answer hint
Git history is immutable: anyone can view past commits even if the file is deleted. The key is accessible in the commit log. You must regenerate the key immediately at platform.openai.com/account/api-keys to invalidate the old one.