The ChatGPT API lets you integrate OpenAI’s powerful language models into your own applications, automations, and workflows with just a few lines of code. This beginner’s guide walks you through getting started with the ChatGPT API in 2026, from setup to your first working application.
What is the ChatGPT API?
The ChatGPT API is a programming interface that lets developers send prompts to OpenAI’s language models and receive AI-generated responses. Unlike the ChatGPT website, the API lets you build custom applications, automate workflows, and process data at scale.
Getting Started: Setup and Authentication
Step 1: Get Your API Key
# Setting up your API key:
1. Go to platform.openai.com
2. Create an account or sign in
3. Navigate to API Keys section
4. Click "Create new secret key"
5. Copy and store it securely (you won't see it again)
# Set as environment variable (recommended):
export OPENAI_API_KEY="your-api-key-here"
Step 2: Install the Python Library
# Install OpenAI Python package:
pip install openai
# Verify installation:
python -c "import openai; print(openai.__version__)"
Step 3: Your First API Call
# Basic API call in 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": "Explain APIs in one paragraph."}
]
)
print(response.choices[0].message.content)
Understanding the API Structure
Messages Format
# The messages array structure:
messages = [
{
"role": "system", # Sets AI behavior
"content": "You are a Python tutor for beginners."
},
{
"role": "user", # Your input
"content": "What is a variable?"
},
{
"role": "assistant", # Previous AI response
"content": "A variable is like a labeled box..."
},
{
"role": "user", # Follow-up question
"content": "Show me an example."
}
]
Key Parameters
# Temperature (creativity control):
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a poem"}],
temperature=0.9, # Higher = more creative (0-2)
)
# For factual/precise tasks:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What is 2+2?"}],
temperature=0.1, # Lower = more deterministic
)
# Max tokens (response length):
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Summarize this"}],
max_tokens=500 # Limit response length
)
Practical API Projects for Beginners
Project 1: Simple Chatbot
# Building a chatbot with conversation history:
from openai import OpenAI
client = OpenAI()
conversation = [
{"role": "system", "content": "You are a friendly cooking assistant."}
]
def chat(user_message):
conversation.append({"role": "user", "content": user_message})
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=conversation
)
assistant_message = response.choices[0].message.content
conversation.append({"role": "assistant", "content": assistant_message})
return assistant_message
# Usage:
print(chat("I have chicken, rice, and broccoli. What can I make?"))
print(chat("How long should I cook the chicken?"))
Project 2: Text Summarizer
# Bulk text summarization:
from openai import OpenAI
client = OpenAI()
def summarize(text, style="concise"):
prompts = {
"concise": "Summarize in 2-3 sentences:",
"bullet": "Summarize as 5 key bullet points:",
"eli5": "Explain this like I'm 10 years old:"
}
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": prompts[style]},
{"role": "user", "content": text}
],
max_tokens=200
)
return response.choices[0].message.content
# Usage:
article = "Your long article text here..."
print(summarize(article, "bullet"))
Project 3: Email Generator
# Automated email drafting:
from openai import OpenAI
client = OpenAI()
def generate_email(scenario, details):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": """You are a professional
email writer. Be concise, professional, and action-oriented."""},
{"role": "user", "content": f"""Write an email for this
scenario: {scenario}
Details: {details}
Include subject line."""}
]
)
return response.choices[0].message.content
# Usage:
print(generate_email(
"Follow up after networking event",
"Met John at TechConf, discussed AI collaboration,
he mentioned his team needs ML consulting"
))
Project 4: Data Processing
# Process structured data with AI:
from openai import OpenAI
import json
client = OpenAI()
def extract_info(text):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": """Extract structured data
and return ONLY valid JSON with these fields:
name, email, company, role, sentiment, key_topics"""},
{"role": "user", "content": text}
],
response_format={"type": "json_object"}
)
return json.loads(response.choices[0].message.content)
# Usage:
feedback = "Hi, I'm Sarah from Acme Corp. As VP of Engineering,
I'm impressed with your API but concerned about pricing..."
print(extract_info(feedback))
Using the API with JavaScript/Node.js
# Node.js setup:
npm install openai
# Basic Node.js API call:
import OpenAI from 'openai';
const openai = new OpenAI(); // Uses OPENAI_API_KEY env
async function askAI(question) {
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: question }
]
});
return response.choices[0].message.content;
}
const answer = await askAI('What is machine learning?');
console.log(answer);
Error Handling and Best Practices
# Robust error handling:
from openai import OpenAI, APIError, RateLimitError
import time
client = OpenAI()
def safe_api_call(messages, max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
return response.choices[0].message.content
except RateLimitError:
wait = 2 ** attempt
print(f"Rate limited. Waiting {wait}s...")
time.sleep(wait)
except APIError as e:
print(f"API error: {e}")
return None
return None
# Cost management tips:
# 1. Use gpt-4o-mini for simple tasks (10x cheaper)
# 2. Set max_tokens to control response length
# 3. Cache responses for repeated queries
# 4. Use streaming for better user experience
# Streaming responses:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
FAQ
Q: How much does the ChatGPT API cost?
A: Pricing is per token (roughly 4 characters). GPT-4o costs about $2.50 per million input tokens and $10 per million output tokens. GPT-4o-mini is much cheaper at $0.15/$0.60 per million tokens. For a typical chatbot conversation, expect costs of $0.01-0.05 per exchange with GPT-4o-mini.
Q: Can I use the API for commercial applications?
A: Yes, OpenAI’s terms allow commercial use. You can build and sell applications powered by the API. However, you must comply with their usage policies, which prohibit certain content types. Review the OpenAI usage policies before launching commercially.
Q: What’s the difference between the ChatGPT website and the API?
A: The website is for interactive conversations with a UI. The API is for building applications — it gives you programmatic access to the models with more control over parameters, no UI constraints, and the ability to process data at scale. The API also lets you use the models in your own custom interfaces and workflows.