How to Use OpenAI's API: Beginner Tutorial
How to Use OpenAI’s API: Beginner Tutorial
The OpenAI API gives you programmatic access to GPT-4o, o3, DALL-E, and other models. This tutorial walks you through setup, your first API call, and common patterns. You will be up and running in 15 minutes.
AI model comparisons are based on publicly available benchmarks and editorial testing. Results may vary by use case.
Prerequisites
- A computer with internet access
- Basic familiarity with the command line or Python
- A credit card for billing (pay-as-you-go)
Step 1: Create an OpenAI Account
- Go to platform.openai.com
- Sign up for an account
- Add a payment method
- Set a usage limit to avoid unexpected bills
Step 2: Get Your API Key
- Navigate to “API Keys” in your account settings
- Click “Create new secret key”
- Copy and store the key securely
Security note: Store your API key as an environment variable. Never commit it to code repositories.
export OPENAI_API_KEY="your-key-here"
Step 3: Install the SDK
Python
pip install openai
TypeScript/JavaScript
npm install openai
Step 4: Make Your 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": "user", "content": "What is the capital of France?"}
]
)
print(response.choices[0].message.content)
TypeScript
import OpenAI from 'openai';
const client = new OpenAI(); // Uses OPENAI_API_KEY env variable
const response = await client.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "user", content: "What is the capital of France?" }
]
});
console.log(response.choices[0].message.content);
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": "user", "content": "What is the capital of France?"}
]
}'
Step 5: Add a System Message
System messages define the AI’s behavior:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful data analyst. Be concise and use bullet points."},
{"role": "user", "content": "Analyze this sales data: Q1: $500K, Q2: $620K, Q3: $580K, Q4: $710K"}
]
)
Prompt Engineering 101: Get Better Results from Any AI
Step 6: Enable Streaming
stream = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "Write a short poem about programming."}
],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Available Models
| Model | Best For | Price (input/output per 1M) |
|---|---|---|
| gpt-4o | General purpose, multimodal | $2.50 / $10.00 |
| gpt-4o-mini | Budget, fast | $0.15 / $0.60 |
| o3 | Hard reasoning, math | $10.00 / $40.00 |
| o3-mini | Budget reasoning | $1.10 / $4.40 |
AI API Pricing Comparison: Cost Per Million Tokens
Key Parameters
| Parameter | Purpose | Values |
|---|---|---|
model | Which model | gpt-4o, gpt-4o-mini, o3 |
max_tokens | Max output length | 1024 for short, 4096 for long |
temperature | Creativity | 0.0 (focused) to 1.0 (creative) |
response_format | Output format | {"type": "json_object"} for JSON |
stream | Real-time output | true / false |
Common Patterns
Image Generation (DALL-E 3)
response = client.images.generate(
model="dall-e-3",
prompt="A serene mountain landscape at sunset, photorealistic",
size="1024x1024",
quality="standard",
n=1
)
image_url = response.data[0].url
Vision (Image Understanding)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image?"},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
]
}]
)
Function Calling
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
tools=[{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}
}]
)
Error Handling
from openai import OpenAI, RateLimitError, APIError
try:
response = client.chat.completions.create(...)
except RateLimitError:
print("Rate limited. Wait and retry.")
except APIError as e:
print(f"API error: {e}")
Key Takeaways
- The OpenAI API provides access to GPT-4o, o3, DALL-E, and other models via simple REST calls.
- Start with GPT-4o for general tasks and gpt-4o-mini for budget-friendly applications.
- System messages control the AI’s behavior and are the highest-leverage configuration point.
- Function calling enables AI to interact with external tools and APIs.
- Set usage limits in your account to avoid unexpected bills.
Next Steps
- Compare with the Claude API: How to Use Claude’s API: Beginner Tutorial.
- Build your first AI app: Building Your First AI App: No-Code to Full-Stack Options.
- Learn prompt engineering for better results: Prompt Engineering 101: Get Better Results from Any AI.
- Compare API pricing across providers: AI API Pricing Comparison: Cost Per Million Tokens.
This content is for informational purposes only and reflects independently researched comparisons. AI model capabilities change frequently — verify current specs with providers. Not professional advice.