OpenAI API
Interact with OpenAI models via the REST API — chat, tools, vision, embeddings, and more.
Authentication
All requests require a Bearer token in the Authorization header.
export OPENAI_API_KEY="[api_key]"
curl https://api.openai.com/v1/models \
-H "Authorization: Bearer $OPENAI_API_KEY"
Chat Completions
Basic Completion
Parameters:
model(Required): ID of the model to use.messages(Required): Array of message objects withroleandcontent.max_tokens(Optional): Maximum tokens to generate.
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "[model]",
"messages": [
{"role": "user", "content": "[prompt]"}
]
}'
With System Prompt
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "[model]",
"messages": [
{"role": "system", "content": "You are a concise technical writer. Reply in plain text only."},
{"role": "user", "content": "[prompt]"}
],
"temperature": 0.2,
"max_tokens": 512
}'
Multi-Turn Conversation
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "[model]",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is Rust ownership?"},
{"role": "assistant", "content": "Rust ownership is a set of rules..."},
{"role": "user", "content": "Give me a concrete example."}
]
}'
Streaming Response
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "[model]",
"stream": true,
"messages": [
{"role": "user", "content": "[prompt]"}
]
}'
💡 Tip: Each streamed chunk is a
data:SSE event. The stream ends withdata: [DONE].
Structured Outputs
Force the model to return valid JSON matching an exact schema.
Parameters:
response_format.type: Set to"json_schema"to enable structured output.strict: Set totrueto guarantee schema adherence.
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "gpt-4o-2024-08-06",
"messages": [
{"role": "user", "content": "Extract name, age and job from: John Doe, 32, engineer"}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "person",
"strict": true,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"job": {"type": "string"}
},
"required": ["name","age","job"],
"additionalProperties": false
}
}
}
}'
Function Calling / Tools
Define and Call a Tool
Parameters:
tools(Optional): Array of tool definitions.tool_choice(Optional):"auto","none", or{"type":"function","function":{"name":"fn"}}.
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "[model]",
"messages": [
{"role": "user", "content": "What is the weather in Tokyo?"}
],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City and country, e.g. Tokyo, Japan"},
"unit": {"type": "string", "enum": ["celsius","fahrenheit"]}
},
"required": ["location"]
}
}
}],
"tool_choice": "auto"
}'
Submit Tool Result
After calling the tool locally, return the result to continue the conversation:
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "[model]",
"messages": [
{"role": "user", "content": "What is the weather in Tokyo?"},
{"role": "assistant", "content": null,
"tool_calls": [{
"id": "call_abc123", "type": "function",
"function": {"name": "get_weather", "arguments": "{\"location\":\"Tokyo, Japan\"}"}
}]
},
{"role": "tool", "tool_call_id": "call_abc123", "content": "{\"temp\":22, \"condition\":\"Sunny\"}"}
],
"tools": [{"type":"function","function":{"name":"get_weather","description":"...","parameters":{}}}]
}'
Vision
Analyze an Image URL
Parameters:
detail(Optional):"low"(fast, fixed cost) or"high"(full resolution, tiles).
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "gpt-4o",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image in detail."},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg", "detail": "high"}}
]
}]
}'
Analyze a Local Image (Base64)
IMG_B64=$(base64 -w 0 /path/to/image.png)
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "gpt-4o",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "What is shown here?"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,'"$IMG_B64"'"}}
]
}]
}'
Embeddings
Parameters:
input(Required): String or array of strings/tokens to embed.dimensions(Optional): Shorten embedding length (text-embedding-3-*only).
curl https://api.openai.com/v1/embeddings \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "text-embedding-3-large",
"input": "The quick brown fox jumps over the lazy dog",
"dimensions": 512
}'
Batch Embeddings
curl https://api.openai.com/v1/embeddings \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "text-embedding-3-large",
"input": ["First sentence", "Second sentence", "Third sentence"]
}'
Image Generation (DALL-E 3)
Parameters:
quality(Optional):"standard"or"hd".style(Optional):"vivid"(hyper-real) or"natural"(realistic).size(Optional):"1024x1024","1792x1024", or"1024x1792".
curl https://api.openai.com/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{
"model": "dall-e-3",
"prompt": "A photorealistic satellite image of a server farm surrounded by forest, golden hour",
"size": "1792x1024",
"quality": "hd",
"style": "natural",
"n": 1
}'
Audio
Transcribe Audio (Whisper)
Parameters:
file(Required): Audio file (mp3, mp4, wav, webm, etc.).language(Optional): ISO-639-1 code (e.g."en") for improved accuracy.
curl https://api.openai.com/v1/audio/transcriptions \
-H "Authorization: Bearer [api_key]" \
-F model="whisper-1" \
-F language="en" \
-F file=@recording.mp3
Text-to-Speech
Parameters:
voice(Required):alloy,echo,fable,onyx,nova,shimmer.speed(Optional): Range 0.25–4.0.
curl https://api.openai.com/v1/audio/speech \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{"model":"tts-1-hd","input":"Hello world.","voice":"onyx","speed":1.0}' \
--output speech.mp3
Moderation
Check whether content violates OpenAI usage policies:
curl https://api.openai.com/v1/moderations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer [api_key]" \
-d '{"model":"omni-moderation-latest","input":"[text to check]"}'
Models Reference
| Model | Context | Best For |
|---|---|---|
gpt-4o | 128k | Multimodal, reasoning, tools |
gpt-4o-mini | 128k | Fast, cost-efficient tasks |
o1 | 200k | Deep multi-step reasoning |
o3-mini | 200k | Affordable advanced reasoning |
text-embedding-3-large | 8k | Highest-quality embeddings |
text-embedding-3-small | 8k | Fast, cost-efficient embeddings |
dall-e-3 | — | Image generation |
whisper-1 | — | Speech-to-text transcription |
tts-1-hd | — | High-quality text-to-speech |
Key Parameters
| Parameter | Type | Range | Description |
|---|---|---|---|
temperature | float | 0.0–2.0 | Randomness (0 = deterministic) |
top_p | float | 0.0–1.0 | Nucleus sampling probability |
max_tokens | integer | 1–context | Max tokens to generate |
frequency_penalty | float | -2.0–2.0 | Penalise repeated tokens |
presence_penalty | float | -2.0–2.0 | Penalise already-used topics |
seed | integer | any | Reproducible outputs (best-effort) |
n | integer | 1–∞ | Number of completion choices |
💡 Tip: Do not set both
temperatureandtop_pat the same time — adjust only one.
Error Handling
| HTTP Code | Error Code | Solution |
|---|---|---|
| 400 | invalid_request_error | Check required params and types |
| 401 | authentication_error | Verify API key or org ID |
| 403 | permission_error | Check key scope / tier |
| 404 | model_not_found | Verify model ID and access tier |
| 429 | rate_limit_exceeded | Implement exponential backoff |
| 500 | server_error | Retry; report if persistent |