How to Format JSON for OpenAI API Requests (With Examples)
Master the exact JSON structure for ChatGPT, GPT-4, and other OpenAI models — with working examples and common error fixes.
🛠️ Validate Your API JSON
Format and validate your OpenAI API request JSON before making the call — catch errors early.
Open JSON Formatter →The OpenAI API (including ChatGPT, GPT-4, and GPT-4o) expects precisely formatted JSON request bodies. A single syntax error, wrong field name, or improper escaping will result in a 400 Bad Request error. This guide covers the exact JSON structure, working examples, and how to avoid the most common formatting mistakes.
Basic OpenAI API JSON Structure
All OpenAI chat completion requests follow this core structure:
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello! How are you?"
}
],
"temperature": 0.7,
"max_tokens": 150
}
Required fields:
model— The AI model to use (e.g., "gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo")messages— Array of conversation messages
Optional fields:
temperature— Controls randomness (0.0 to 2.0, default 1.0)max_tokens— Maximum response lengthstream— Enable streaming responses (true/false)stop— Stop sequences to end generation
Message Roles and Structure
The messages array is the heart of your API request. Each message object requires two fields:
System Messages
Define the AI's behavior and context:
{
"role": "system",
"content": "You are a Python expert who explains code clearly and concisely."
}
User Messages
Your prompts and questions:
{
"role": "user",
"content": "Write a function to reverse a string in Python."
}
Assistant Messages
Previous AI responses (for conversation context):
{
"role": "assistant",
"content": "Here's a simple function to reverse a string:\n\ndef reverse_string(s):\n return s[::-1]"
}
Real-World Examples
Simple Question
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "What's the capital of France?"
}
]
}
Code Generation with Context
{
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "You are a senior JavaScript developer. Write clean, modern ES6+ code with comments."
},
{
"role": "user",
"content": "Create a function that fetches user data from an API and handles errors gracefully."
}
],
"temperature": 0.3,
"max_tokens": 500
}
Multi-turn Conversation
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You are a helpful math tutor."
},
{
"role": "user",
"content": "How do I solve quadratic equations?"
},
{
"role": "assistant",
"content": "Quadratic equations have the form ax² + bx + c = 0. You can solve them using the quadratic formula: x = (-b ± √(b² - 4ac)) / 2a"
},
{
"role": "user",
"content": "Can you show me an example with x² - 5x + 6 = 0?"
}
],
"temperature": 0.2
}
Handling Special Characters
JSON requires proper escaping of special characters. Here's what you need to know:
⚠️ Common Escaping Mistakes
Unescaped quotes, newlines, and backslashes are the #1 cause of API request failures.
String Escaping Rules
- Double quotes:
"He said \"Hello\"" - Newlines:
"Line 1\nLine 2" - Tabs:
"Name:\tJohn" - Backslashes:
"Path: C:\\Users\\file.txt"
Example with Special Characters
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "Analyze this code:\n\ndef greet(name):\n print(f\"Hello, {name}!\")\n return True"
}
]
}
Programming Language Examples
Python (using requests)
import requests
import json
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
}
data = {
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": "Write a haiku about coding"}
],
"temperature": 0.8
}
response = requests.post(url, headers=headers, json=data)
print(response.json())
JavaScript (Node.js)
const fetch = require('node-fetch');
const requestBody = {
model: "gpt-4o-mini",
messages: [
{
role: "system",
content: "You are a creative writer."
},
{
role: "user",
content: "Write a short story about a robot learning to paint."
}
],
max_tokens: 200
};
fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => response.json())
.then(data => console.log(data));
cURL Command Line
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "Explain recursion in programming"
}
],
"temperature": 0.7
}'
Common JSON Formatting Errors
These mistakes will cause your API calls to fail. For more details on JSON validation, check our complete guide to fixing JSON errors.
1. Trailing Commas
❌ Wrong
{"model": "gpt-4", "temperature": 0.5,} — trailing comma is invalid JSON
✅ Correct:
{
"model": "gpt-4o-mini",
"temperature": 0.5
}
2. Single Quotes
❌ Wrong
{'model': 'gpt-4'} — JSON requires double quotes only
✅ Correct:
{
"model": "gpt-4o-mini"
}
3. Unescaped Quotes in Content
❌ Wrong
"content": "Say "hello" to the user" — breaks JSON parsing
✅ Correct:
{
"content": "Say \"hello\" to the user"
}
4. Missing Commas
❌ Wrong
{"model": "gpt-4" "temperature": 0.7} — missing comma between fields
✅ Correct:
{
"model": "gpt-4o-mini",
"temperature": 0.7
}
API-Specific Formatting for Different Providers
While this guide focuses on OpenAI, other AI APIs use similar JSON structures with variations:
Claude (Anthropic)
{
"model": "claude-3-sonnet-20240229",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Hello Claude"
}
]
}
Gemini (Google)
{
"contents": [
{
"parts": [
{"text": "Write a story about a dragon"}
]
}
],
"generationConfig": {
"temperature": 0.9,
"maxOutputTokens": 2048
}
}
Validation and Testing Tips
- Validate before sending: Use our JSON formatter to check syntax before making API calls.
- Test with minimal requests: Start with the simplest possible JSON to verify your setup works.
- Check API documentation: Model names and available parameters change over time.
- Use proper content-type: Always set
Content-Type: application/jsonin your headers. - Handle API errors gracefully: Parse error responses to understand what went wrong.
Advanced Parameters
Streaming Responses
{
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": "Write a long essay about artificial intelligence"}
],
"stream": true
}
Function Calling
{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "What's the weather like in Boston?"}
],
"functions": [
{
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name"
}
},
"required": ["location"]
}
}
]
}
Performance and Cost Optimization
- Use appropriate models: GPT-4o-mini is faster and cheaper for simpler tasks
- Set max_tokens: Prevent unexpectedly long (expensive) responses
- Lower temperature for consistent outputs: Reduces need for retries
- Minimize message history: Only include context that's actually needed
Perfect Your API Requests
Format, validate, and optimize your OpenAI API JSON before sending — save time and API credits.
Validate Your JSON →Understanding JSON formatting for AI APIs is essential for modern development. Whether you're building chatbots, content generation tools, or AI-powered applications, properly formatted requests ensure reliable API interactions and better user experiences. For more JSON tips, read our guide on JSON formatting and validation, or learn about comprehensive JSON validation techniques.
Recommended Tools & Resources
Level up your workflow with these developer tools:
Try DigitalOcean → Try Neon Postgres → Clean Code by Robert C. Martin →Dev Tools Digest
Get weekly developer tools, tips, and tutorials. Join our developer newsletter.
Frequently Asked Questions
What JSON format does OpenAI API expect?
OpenAI API expects valid JSON with specific required fields like 'model' and 'messages' for chat completions. The 'messages' array contains objects with 'role' (system/user/assistant) and 'content' fields. Optional parameters include 'temperature', 'max_tokens', and 'stream'.
How do I handle special characters in OpenAI API JSON?
Special characters like quotes, newlines, and backslashes must be properly escaped in JSON strings. Use \" for quotes, \n for newlines, \\ for backslashes, and \t for tabs. Most programming languages handle this automatically when encoding to JSON.
Why is my OpenAI API request failing with invalid JSON?
Common causes include: trailing commas (not allowed in JSON), single quotes instead of double quotes, unescaped special characters, missing commas between fields, or malformed nested objects. Use a JSON validator to identify syntax errors before making API calls.
Can I use the same JSON format for Claude and OpenAI APIs?
While both use JSON, the request formats differ. OpenAI uses 'messages' array with role/content objects, while Claude's API has different field names and structure. However, the core JSON formatting rules (escaping, syntax) remain the same across all APIs.