Getting Started with OpenAI API
The OpenAI API gives you programmatic access to GPT models. This topic covers setup, authentication, and building your first AI-powered application.
Setting Up
1. Create an Account
Sign up at platform.openai.com and add a payment method. New accounts get free credits to start.
2. Get Your API Key
Navigate to API Keys in your dashboard and create a new secret key. Store it securely — you won't be able to see it again.
# Set as environment variable
export OPENAI_API_KEY="sk-your-key-here"3. Install the SDK
# Python
pip install openai
# Node.js
npm install openaiYour First API Call
Python
from openai import OpenAI
client = OpenAI() # Uses OPENAI_API_KEY env variable
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"}
]
)
print(response.choices[0].message.content)
# Output: "The capital of France is Paris."Node.js
import OpenAI from 'openai';
const openai = new OpenAI(); // Uses OPENAI_API_KEY env variable
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "What is the capital of France?" }
]
});
console.log(response.choices[0].message.content);Understanding the Messages Format
The chat API uses a conversation format with three roles:
messages = [
# System message: Sets the AI's behavior
{"role": "system", "content": "You are a Python tutor."},
# User messages: What the human says
{"role": "user", "content": "How do I read a file?"},
# Assistant messages: Previous AI responses (for context)
{"role": "assistant", "content": "You can use open()..."},
# Continue the conversation
{"role": "user", "content": "What about binary files?"}
]Key Parameters
response = client.chat.completions.create(
model="gpt-4o", # Model to use
messages=messages, # Conversation history
temperature=0.7, # Creativity (0-2)
max_tokens=1000, # Max response length
top_p=1.0, # Nucleus sampling
frequency_penalty=0.0, # Reduce repetition
presence_penalty=0.0, # Encourage new topics
stop=["\n\n"], # Stop sequences
)Model Options
| Model | Best For | Cost |
|---|---|---|
gpt-4o | Most capable, multimodal | $$ |
gpt-4o-mini | Fast, cost-effective | $ |
gpt-4-turbo | Complex reasoning | $$$ |
o1 | Advanced reasoning, math | $$$$ |
Streaming Responses
For real-time output, use streaming:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a haiku about coding"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")Working with Images (Vision)
GPT-4o can understand images:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/photo.jpg"
}
}
]
}
]
)Structured Output (JSON Mode)
Force the model to return valid JSON:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": "Extract product info as JSON with keys: name, price, category"
},
{
"role": "user",
"content": "The iPhone 15 Pro costs $999 and is a smartphone."
}
],
response_format={"type": "json_object"}
)
import json
data = json.loads(response.choices[0].message.content)
# {"name": "iPhone 15 Pro", "price": 999, "category": "smartphone"}Error Handling
from openai import OpenAI, APIError, RateLimitError, APIConnectionError
client = OpenAI()
try:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}]
)
except RateLimitError:
print("Rate limit hit — wait and retry")
except APIConnectionError:
print("Network issue — check your connection")
except APIError as e:
print(f"API error: {e.status_code} - {e.message}")Tracking Usage and Costs
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}]
)
usage = response.usage
print(f"Input tokens: {usage.prompt_tokens}")
print(f"Output tokens: {usage.completion_tokens}")
print(f"Total tokens: {usage.total_tokens}")Best Practices
- Store API keys securely — Use environment variables, never hardcode
- Set max_tokens — Prevent unexpectedly long (expensive) responses
- Use the cheapest model that works — Start with gpt-4o-mini, upgrade if needed
- Implement retries — Network and rate limit errors are transient
- Cache responses — Identical prompts don't need repeated API calls
- Monitor usage — Set billing alerts on your OpenAI dashboard
Quick Reference
# Minimal setup
from openai import OpenAI
client = OpenAI()
# Simple completion
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Your prompt here"}],
temperature=0.7,
max_tokens=500
)
answer = response.choices[0].message.contentIn the next topic, we'll explore the Anthropic Claude API, which offers a different approach with longer context windows and a focus on safety.