OpenAI API Guide 2025: Setup, Models & Best Practices
A practical guide to the OpenAI API for developers — getting your API key, understanding the model lineup, making your first chat completion request, handling rate limits, and choosing between GPT-4o, o3, and Anthropic Claude.
Getting Your API Key
- Go to platform.openai.com and sign in (or create an account)
- Navigate to API Keys in the left sidebar
- Click Create new secret key — give it a name and set project scope if using Projects
- Copy the key immediately — it begins with
sk-...and is shown only once - Go to Billing → Add payment method and purchase $5+ in credits to unlock the API
Security tip: Never hardcode your API key in source code. Use environment variables: export OPENAI_API_KEY=sk-... or a .env file excluded from git.
Models Overview (2025)
| Model | Context | Best for | Price (input/output per 1M tokens) |
|---|---|---|---|
| gpt-4o | 128k | General use, vision, audio | $2.50 / $10 |
| gpt-4o-mini | 128k | Fast, cheap, good quality | $0.15 / $0.60 |
| o3 | 200k | Hard reasoning, math, code | $10 / $40 |
| o4-mini | 200k | Fast reasoning, cheaper than o3 | $1.10 / $4.40 |
| dall-e-3 | — | Image generation | $0.04–$0.12 per image |
| whisper-1 | — | Speech to text, transcription | $0.006 per minute |
| tts-1 / tts-1-hd | — | Text to speech | $15 / $30 per 1M chars |
For reasoning-heavy tasks, see our OpenAI o3 guide and GPT-4o guide for deeper dives.
Chat Completions — First Request
# curl
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain REST APIs in 2 sentences."}
]
}' # Python (openai SDK)
pip install openai
from openai import OpenAI
client = OpenAI() # uses OPENAI_API_KEY env var
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain REST APIs in 2 sentences."}
]
)
print(response.choices[0].message.content)
print(f"Tokens used: {response.usage.total_tokens}") Streaming Responses
Streaming returns tokens as they're generated — critical for chat UIs that need to feel responsive:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Tell me a joke."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True) Function Calling (Tool Use)
Pass tool definitions and the model outputs structured JSON when it decides to call a tool:
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
}
}]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
tools=tools,
tool_choice="auto" # model decides when to call
) Rate Limits & Tier System
| Tier | Requirement | GPT-4o RPM | GPT-4o TPM |
|---|---|---|---|
| Free | New account | 3 | 200k |
| Tier 1 | $5 paid | 500 | 30k |
| Tier 2 | $50 + 7 days | 5,000 | 450k |
| Tier 3 | $100 + 7 days | 5,000 | 800k |
| Tier 5 | $1,000 + 30 days | 10,000 | 2M |
Rate limits apply per model per minute. When you hit limits, you get HTTP 429. Implement exponential backoff: wait 1s, 2s, 4s between retries. For high-volume production use, request limit increases via the platform dashboard.
Common Error Codes
| Code | Meaning | Fix |
|---|---|---|
| 401 | Invalid API key | Check key is correct and not expired |
| 429 | Rate limit exceeded | Exponential backoff; check tier limits |
| 500 | OpenAI server error | Retry after 30s; check OpenAI status |
| 503 | Service overloaded | Retry with backoff; consider model fallback |
| 400 | Bad request (context too long) | Reduce prompt size; use tiktoken to count tokens |
Token Counting with tiktoken
Count tokens before sending a request to avoid 400 errors on long prompts:
pip install tiktoken
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")
tokens = enc.encode("Your prompt text here...")
print(f"Token count: {len(tokens)}") # GPT-4o limit: 128,000 OpenAI vs Anthropic API
| Factor | OpenAI API | Anthropic API |
|---|---|---|
| Best model | o3 (reasoning), GPT-4o (general) | Claude Opus 4, claude-sonnet-4-6 |
| Context window | 128k (GPT-4o), 200k (o3) | 200k (all models) |
| Multimodal | Text, images, audio (native) | Text + images |
| Tool use | ✅ Function calling | ✅ Tool use |
| Image generation | ✅ DALL-E 3 | ❌ |
| Coding tasks | Excellent (o3, o4-mini) | Excellent (Claude Sonnet 4) |
| Prompt caching | ✅ Automatic | ✅ Explicit cache_control |
For a deeper comparison, see OpenAI vs Anthropic API. Also explore OpenAI alternatives if you're evaluating other providers.
Monitor OpenAI API Status
The OpenAI API has degradations and outages that affect production apps. Prismix tracks real-time status, historical uptime, and sends instant alerts when the API becomes unavailable.
Monitor OpenAI Status Free →