ChatGPT API Tutorial: Build Your First AI-Powered App in 1 Hour
Step-by-step ChatGPT API tutorial for beginners: get an API key, make your first call, understand tokens and pricing, and build a working AI app in under an hour using Python or Node.js.
Get more content like this on Telegram!
Daily AI tips, notes & resources — free
ChatGPT API Tutorial: Build Your First AI-Powered App in 1 Hour
Using ChatGPT via the web interface has a ceiling. The API removes it.
With the API, you build AI into your own applications — custom interfaces, automated workflows, AI features in products you're building, or scripted processes that run without a human typing prompts.
I'll walk you through everything: account setup, your first API call, understanding the cost model, and a complete working application by the end of the tutorial.
Prerequisites: Basic programming knowledge in Python or JavaScript. No AI experience required.
Step 1: Account Setup and API Key
- Go to platform.openai.com and create an account (separate from your ChatGPT account, though you can use the same credentials)
- Navigate to Settings → Billing and add a payment method
- Optionally set a usage limit in Billing — I recommend $10–$20 for learning to prevent unexpected charges
- Go to API Keys → Create new secret key
- Copy the key immediately — you won't be able to see it again
Security: Never commit API keys to version control. Store them in environment variables.
Step 2: Install the OpenAI Library
Python:
pip install openai
Node.js:
npm install openai
Step 3: Your First API Call
Python:
from openai import OpenAI
client = OpenAI(api_key="your-api-key-here") # Or use os.environ["OPENAI_API_KEY"]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What are three tips for learning to code faster?"}
]
)
print(response.choices[0].message.content)
Node.js:
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const response = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "What are three tips for learning to code faster?" }
]
});
console.log(response.choices[0].message.content);
Run this and you'll get an AI-generated response. That's the core of the API.
Understanding the Response Structure
The API returns an object with this structure:
{
"id": "chatcmpl-...",
"choices": [{
"message": {
"role": "assistant",
"content": "Here are three tips..."
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 28,
"completion_tokens": 145,
"total_tokens": 173
}
}
Key parts:
choices[0].message.content— the actual response textusage.prompt_tokens— tokens in your inputusage.completion_tokens— tokens in the responseusage.total_tokens— total (what you're billed for)
Understanding Tokens and Pricing
What's a token? Roughly 4 characters of English text. "Hello, world!" is about 4 tokens. A 1,000-word article is roughly 1,300 tokens.
Model pricing (approximate, as of 2026):
| Model | Input (per 1M tokens) | Output (per 1M tokens) | Best for |
|---|---|---|---|
| gpt-4o-mini | $0.15 | $0.60 | Development, high-volume, simple tasks |
| gpt-4o | $5.00 | $15.00 | Complex reasoning, quality-critical tasks |
Cost example: A chatbot processing 1,000 conversations per day, each averaging 500 input + 300 output tokens:
- gpt-4o-mini: ~$0.21/day
- gpt-4o: ~$7.00/day
For most applications, start with gpt-4o-mini and upgrade only if quality isn't sufficient.
The System Prompt: Your Most Powerful Tool
The system prompt defines how the model behaves. It's the difference between a generic AI and an AI that acts like your specific assistant.
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": """You are a customer service agent for TechStore, an electronics retailer.
Only answer questions related to our products and policies.
If asked about something unrelated, politely redirect to relevant topics.
Always be helpful and professional.
Our return policy: 30-day returns on all items with original packaging."""
},
{"role": "user", "content": "Can I return headphones I bought 3 weeks ago?"}
]
)
This single system prompt makes the model behave as a constrained, company-specific assistant.
Building a Complete App: AI-Powered Content Summarizer
Let's build something useful: a script that reads an article URL, fetches the content, and generates a summary.
Python (complete working script):
import os
from openai import OpenAI
import requests
from bs4 import BeautifulSoup
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
def fetch_article(url):
"""Fetch article text from URL"""
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
paragraphs = soup.find_all('p')
text = ' '.join([p.get_text() for p in paragraphs])
return text[:4000] # Limit to first 4000 chars to manage tokens
def summarize_article(text, summary_type="brief"):
"""Generate article summary using ChatGPT API"""
if summary_type == "brief":
instruction = "Summarize this article in 3 bullet points. Be concise."
elif summary_type == "detailed":
instruction = "Provide a detailed summary: main topic, key arguments, and conclusion."
elif summary_type == "tldr":
instruction = "Write a one-sentence TL;DR for this article."
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You are a skilled editor who creates accurate, concise article summaries."
},
{
"role": "user",
"content": f"{instruction}\n\nArticle text:\n{text}"
}
],
max_tokens=500
)
return response.choices[0].message.content
# Main
if __name__ == "__main__":
url = input("Enter article URL: ")
print("Fetching article...")
article_text = fetch_article(url)
print("\n=== BRIEF SUMMARY ===")
print(summarize_article(article_text, "brief"))
print("\n=== TL;DR ===")
print(summarize_article(article_text, "tldr"))
print(f"\nTokens used: approximately {len(article_text.split()) * 1.3:.0f}")
Dependencies: pip install openai requests beautifulsoup4
This is a complete, working application. Run it, paste in a news article URL, and get a summary.
Multi-Turn Conversations
The API is stateless — each call is independent. To build a conversation, you maintain the message history yourself:
conversation_history = [
{"role": "system", "content": "You are a helpful cooking assistant."}
]
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
break
# Add user message to history
conversation_history.append({"role": "user", "content": user_input})
# Get response
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=conversation_history
)
assistant_message = response.choices[0].message.content
# Add assistant response to history
conversation_history.append({"role": "assistant", "content": assistant_message})
print(f"Assistant: {assistant_message}")
Every request sends the full conversation history — this is how the model maintains context.
Cost implication: Longer conversations cost more because the full history is sent each time. For very long conversations, you may need to truncate older messages.
Error Handling and Best Practices
from openai import OpenAI, RateLimitError, APIError
import time
def safe_api_call(client, messages, model="gpt-4o-mini", retries=3):
for attempt in range(retries):
try:
response = client.chat.completions.create(
model=model,
messages=messages,
timeout=30
)
return response
except RateLimitError:
if attempt < retries - 1:
wait_time = 2 ** attempt # Exponential backoff
print(f"Rate limit hit. Waiting {wait_time}s...")
time.sleep(wait_time)
else:
raise
except APIError as e:
print(f"API error: {e}")
raise
Best practices:
- Always handle rate limits with exponential backoff
- Set
timeouton requests - Use
max_tokensto prevent unexpectedly large (expensive) responses - Store API keys in environment variables, never in code
- Log usage for cost monitoring
Further Reading
- ChatGPT for Academic Research: Citations and Summaries
- ChatGPT Custom Instructions: The Secret Setting 90% of Users Miss
- ChatGPT vs Google Gemini: Which AI Assistant Is Right for You?
- How to Train ChatGPT on Your Own Data (No Code)
- ChatGPT for Personal Finance: Budgeting and Investing Tips
- Best Free AI for Writing Quizzes and Surveys That Capture Leads
- 10 AI Prompt Generators That Help You Write Better Prompts Fast
- How to Use AI to Write Thank You Cards and Letters That Feel Real
Frequently Asked Questions
AiTechWorlds Team
✓ Verified WriterThe AiTechWorlds team is passionate about AI, technology, and education. We create high-quality, research-backed content to help you learn, grow, and succeed in the modern digital world.
Related Articles
10 Advanced ChatGPT Prompting Techniques (Chain of Density and More)
Master advanced ChatGPT prompting with Chain of Density, Chain of Thought, Tree of Thoughts, role stacking, and 6 more expert techniques with real examples.
How to Use AI to Write a Compelling About Us Page (2026)
Use an AI about us page generator to craft a story, mission, and team section that builds trust. Includes 3 templates for startups, freelancers, and agencies.
How to Create AI-Generated Album Cover Art (Free Tools 2026)
Learn how to create AI album cover art for free using top tools in 2026. Genre-specific prompts, Spotify specs, and real tool comparisons inside.
5 AI Image Generators Specialized in Anime Style (2026)
Find the best AI anime generator for 2026. Compare NovelAI, Waifu Diffusion, Leonardo, and more with real accuracy tests and free tier details.