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
Frequently Asked Questions
How do I get started with the ChatGPT API?
OpenAI account → add payment method → generate API key → install openai library → make your first call. Under 30 minutes to first response.
How much does it cost?
GPT-4o-mini: ~$0.15/1M input tokens. GPT-4o: ~$5/1M input tokens. Most small applications cost pennies per day.
What's the difference between ChatGPT and the API?
ChatGPT is the consumer chat interface. The API gives developers programmatic access to build AI into applications.
What languages can I use?
Python and Node.js have official libraries. Any language that makes HTTP requests can use the API.
What is a system prompt?
A "system" role message that defines the model's behavior for the conversation. Your most powerful tool for customizing AI behavior in your application.
Final Thoughts
An hour of work gets you from zero API knowledge to a working AI-powered application. The fundamentals — API call structure, system prompts, token costs, conversation history — cover 80% of what you need for most applications.
From here: explore OpenAI's documentation for advanced features (function calling, structured outputs, file uploads). And for non-developers who want to get maximum value from ChatGPT without coding, ChatGPT Custom Instructions gives you many of the same customization benefits through the regular interface.
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
7 Free AI Tools for Students That Make College Easier
Seven free AI tools that legitimately help students study better, research faster, and write stronger — without academic integrity violations. All tested by students for actual academic use.
Free AI Chatbots Ranked: Which One Gives the Best Answers in 2026?
Free AI chatbots compared and ranked by answer quality, knowledge recency, accuracy, and use case fit. Tested across writing, coding, research, and reasoning tasks.
50 Best Free AI Tools in 2026 That Are Actually Worth Your Time
50 genuinely useful free AI tools across writing, image generation, video, productivity, coding, and research — tested and ranked. No paid upsells disguised as free tiers.
I Spent 100 Hours with ChatGPT-4o — Here's Everything I Learned
A ChatGPT-4o review after 100 hours of real use: writing, coding, analysis, and multimodal tasks. What it does better than GPT-4, where it still falls short, and whether it's worth the upgrade.