The OpenAI API opens up a world of possibilities for building AI-powered applications. This guide walks you through everything from getting your API key to building a real application.
Step 1: Get Your API Key
- Go to platform.openai.com and create an account
- Navigate to API Keys in your account settings
- Click "Create new secret key" and copy it immediately (you won't see it again)
- Store it securely โ never hardcode it in your source files
Step 2: Install the SDK
For Python:
pip install openai
For Node.js:
npm install openai
Step 3: Your First API Call
Python example:
from openai import OpenAI
client = OpenAI(api_key="your-api-key")
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"}
]
)
print(response.choices[0].message.content)
Understanding the Response Object
The API response includes: the message content, token usage (prompt + completion), finish reason (stop, length, content_filter), and model used. Always check response.usage to track costs.
Streaming Responses
For a better user experience, stream responses token by token:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="", flush=True)
Token Management
Tokens are the API's currency. Roughly 1 token = 4 characters. GPT-4o pricing: $5 per 1M input tokens, $15 per 1M output tokens. To reduce costs:
- Keep system prompts concise
- Use
max_tokensto limit response length - Cache repeated context with Prompt Caching feature
- Use GPT-4o-mini for simpler tasks ($0.15/1M input)
Building a Simple Chatbot
Maintain conversation history by keeping the messages array:
messages = [{"role": "system", "content": "You are helpful."}]
while True:
user_input = input("You: ")
messages.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
assistant_message = response.choices[0].message.content
messages.append({"role": "assistant", "content": assistant_message})
print(f"AI: {assistant_message}")
Error Handling Best Practices
- Implement exponential backoff for rate limit errors (429)
- Handle context length exceeded errors (400) by truncating history
- Log all API errors with request IDs for debugging
- Set request timeouts to prevent hanging
Tags
Advertisement
article-mid
Related Articles
ChatGPT for SEO: Complete Beginner's Guide (2026)
Learn how to use ChatGPT for SEO โ from keyword research and content briefs to meta descriptions and technical SEO fixes. Practical guide for beginners.
AI Automation for Beginners: Save 5+ Hours a Week in 2026
A beginner's guide to AI automation โ what it is, the best tools to start with, 5 workflows you can set up today, and common mistakes to avoid.
AI Tools for Learning: Master Any Skill Faster in 2026
How to use AI tools for self-directed learning, language acquisition, professional skill development, and personal knowledge management โ beyond the classroom.