OpenAI API Key: Create, Secure, and Use
What you’ll build
Section titled “What you’ll build”By the end of this guide you will have an OpenAI API key stored in an environment variable, usage limits configured, and a working Python and cURL call that returns a chat completion. The same approach applies to any runtime that reads environment variables.
Prerequisites
Section titled “Prerequisites”| Requirement | Notes |
|---|---|
| OpenAI account | Sign up at platform.openai.com/signup |
| Verified email | Required before creating keys |
| Payment method | Credit card for pay-as-you-go access |
| Python 3.9+ or Node.js 18+ | To run the verification samples |
Step 1 — Create the API key
Section titled “Step 1 — Create the API key”- Sign in at platform.openai.com.
- Click your profile icon (top-right) and select API keys, or go to platform.openai.com/api-keys directly.
- Click + Create new secret key, give it a name (for example
orders-portal-dev), set permissions to All or Restricted as needed, and click Create secret key. - Copy the full key immediately — it starts with
sk-proj-and is shown only once. Close the dialog after copying; there is no way to retrieve it again.
Store it in a password manager or secrets vault before you proceed.
Step 2 — Set usage limits
Section titled “Step 2 — Set usage limits”API calls are billed per token. A runaway loop or leaked key can generate unexpected charges.
- Go to Settings › Billing › Usage limits (or platform.openai.com/account/billing/limits).
- Set a Monthly budget so that requests stop when the limit is reached.
- Enable email alerts at a lower threshold so you get advance warning before hitting the hard cap.
Step 3 — Store the key securely
Section titled “Step 3 — Store the key securely”Linux / macOS (current shell session):
export OPENAI_API_KEY="sk-proj-your-key-here"Windows PowerShell (current session):
$env:OPENAI_API_KEY = "sk-proj-your-key-here".env file for local development (add .env to .gitignore):
OPENAI_API_KEY=sk-proj-your-key-hereLoad it in Python with python-dotenv:
from dotenv import load_dotenvload_dotenv()For production, use your platform’s secret store: AWS Secrets Manager, Azure Key Vault, GitHub Actions Secrets, or equivalent.
Step 4 — Verify the key works
Section titled “Step 4 — Verify the key works”Install the SDK, then run a minimal request to confirm everything is wired correctly.
pip install openaiSave as check_key.py and run with python check_key.py (Python 3.9+):
import openaiimport os
client = openai.OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create( model="gpt-4o-mini", max_tokens=16, messages=[{"role": "user", "content": "Reply with the word VERIFIED."}],)
print(response.choices[0].message.content)# Expected output: VERIFIEDOr use cURL directly:
curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini", "max_tokens": 16, "messages": [{"role": "user", "content": "Reply with the word VERIFIED."}] }'A successful response returns HTTP 200 with choices[0].message.content containing your text.
Available models
Section titled “Available models”| Model family | Typical use |
|---|---|
| GPT-6, GPT-6.1 (Terra / Sol / Astra) | Frontier reasoning, complex multi-step tasks |
| GPT-4o, GPT-4o mini | Balanced general-purpose chat and analysis |
| o3, o4-mini | Deep chain-of-thought reasoning |
text-embedding-3-large / text-embedding-3-small |
Semantic search, RAG |
| Whisper | Audio transcription |
Model names and tiers change frequently. Check platform.openai.com/docs/models for the current list before hardcoding a model string.
Managing keys
Section titled “Managing keys”View keys: The API keys page shows each key’s name, masked value, creation date, and last-used timestamp.
Revoke a key: Click the trash icon and confirm. Any application using that key immediately receives 401 Unauthorized responses.
Rotation policy: Create a replacement key, roll it out to your applications, verify everything works, then delete the old one.
Restricted keys: When creating a key you can limit it to specific endpoints (for example, only Chat completions). Use restricted keys for third-party integrations so a compromised key cannot access billing or fine-tuning endpoints.
Troubleshooting
Section titled “Troubleshooting”| Error | Likely cause | Fix |
|---|---|---|
401 Unauthorized |
Key missing or revoked | Confirm the Authorization: Bearer header is present. Re-check the key value. |
429 Too many requests |
Rate limit exceeded | Add exponential backoff. See rate limits guide. |
429 Quota exceeded |
Monthly spending limit reached | Increase the limit in Billing settings or wait for the billing cycle to reset. |
400 Bad request |
Missing required field | Confirm model, messages, and max_tokens are present in the request body. |
Next steps
Section titled “Next steps”- OpenAI Models guide — GPT-6 family, o-series reasoning models, and embedding models
- OpenAI overview — platform capabilities and use cases
- API Tokens overview — comparison of all supported providers
Official references
Section titled “Official references”- OpenAI Platform — key management, billing, and usage dashboard
- API reference — versioned REST reference
- Models list — current model IDs
- Rate limits guide — tiers and backoff strategies
- Python SDK —
openaipackage on PyPI