Creating an API key: account and project keys
Why this matters
Without an API key, you cannot make any requests to OpenAI's models. Understanding account keys vs. project keys prevents both security leaks and organizational access control problems.
Explanation
What it does: API keys are credentials that authenticate your code to the OpenAI API. An account-level key has access to all projects and usage under your account. A project-level key is scoped to a single project and can be rotated or revoked independently.
How it works: When you create a key in the dashboard, OpenAI generates a 48-character string that you store securely. Your OpenAI Python SDK reads this key (from environment variables or explicit configuration) and includes it in the Authorization header of every API request. The API server validates the key, checks your account status and billing, then processes your request.
When to use it: Account keys are convenient for personal projects and development. Project keys are essential in production: they let you rotate credentials without redeploying code, set usage limits per project, and revoke access instantly if a key is leaked.
Request code
import os
from openai import OpenAI
os.environ['OPENAI_API_KEY'] = 'sk-your-key-here'
client = OpenAI()
response = client.chat.completions.create(
model='gpt-4.1',
messages=[{'role': 'user', 'content': 'Say hello'}],
max_tokens=10
)
print(response.choices[0].message.content) Authentication
1. Go to https://platform.openai.com/account/api-keys 2. Click 'Create new secret key' 3. Choose scope: Account (all projects) or Project (single project only) 4. Copy the key immediately: you cannot view it again 5. Store it in environment variable: export OPENAI_API_KEY='sk-...' 6. Never commit keys to version control: use .env files or CI/CD secrets management
Response shape
| Field | Description |
|---|---|
id | chatcmpl-xyz |
object | chat.completion |
created | 1698765432 |
model | gpt-4.1 |
choices | [object Object] |
usage | [object Object] |
Field guide
id Unique identifier for this API call: store this in logs for debugging
created Unix timestamp of when the response was generated: useful for rate limit tracking
usage.total_tokens The number of tokens billed; this directly determines your cost for this request
finish_reason Why the model stopped generating; 'stop' means normal completion, 'length' means max_tokens was hit (and you were charged for incomplete output)
Setup trap
Setting os.environ['OPENAI_API_KEY'] AFTER creating the OpenAI client will not work. The client reads the key at __init__ time. Always set the environment variable first, or pass api_key explicitly: client = OpenAI(api_key='sk-...').
Cost
Creating an API key itself is free. However, every API call made with that key incurs charges. GPT-4.1 costs ~$0.03 per 1K input tokens and ~$0.06 per 1K output tokens. A leaked key can result in thousands of dollars in charges within hours.
Rate limits
OpenAI applies rate limits per key: free trial accounts are limited to 3 requests per minute. Paid accounts receive higher limits based on spend. If you hit the limit, you'll receive a 429 status code. Project-level keys allow you to set per-project rate limits for better control.
Common gotcha
Creating a key in the dashboard and immediately trying to use it without setting the environment variable or passing it explicitly. Developers often forget that OpenAI() reads OPENAI_API_KEY at instantiation time: if the env var isn't set before client initialization, you'll get 'AuthenticationError: No API key provided.'
Error recovery
AuthenticationError: No API key providedAuthenticationError: Invalid API keyRateLimitError: Rate limit exceededBadRequestError: Quota exceededExperienced dev note
In production, always use project-level keys, not account keys. A compromised account key gives attackers access to your entire account and all billing. Project keys can be rotated independently and scoped to specific projects, cutting blast radius. Also: implement key rotation as a monthly task. Never store keys in config files checked into git: use your deployment platform's secrets manager (GitHub Secrets, AWS Secrets Manager, Kubernetes Secrets, etc.). One leaked key can cost you thousands before you notice.
Check your understanding
If you set OPENAI_API_KEY in a .env file but forget to load it with load_dotenv() before instantiating the OpenAI client, what error will you get, and why?
Show answer hint
The OpenAI client reads OPENAI_API_KEY from the environment at instantiation time. If it's in a .env file but not loaded into os.environ, the client won't see it. You'll receive 'AuthenticationError: No API key provided' because the constructor looks for the environment variable at that moment, not later.