OpenAI API Tutorial | 2026 Complete Guide from API Key to Code Examples
OpenAI API Tutorial | 2026 Complete Guide from API Key to Code Examples
You Love Chatting with ChatGPT, But Did You Know the API Is the Real Productivity Tool?
ChatGPT is great.
But it has one fatal limitation: you can only ask one question at a time and manually copy-paste answers.
What if you need to automatically process 500 customer emails? What if you want to embed AI into your own product? What if you need AI to automatically respond to customers 24/7?
That's when you need the OpenAI API.
The API lets you call GPT-4o, GPT-5, and other models directly with code. No browser needed, no manual operations. Your program becomes your "automated assistant."
This tutorial takes you from applying for an API Key to writing working code, step by step.
Want to get started with AI API quickly? CloudInsight provides technical support & enterprise plans, solving payment and invoicing issues.
OpenAI API Key Application Steps
Answer-First: Applying for an OpenAI API Key takes 5 minutes. Go to platform.openai.com to register, then create a key on the API Keys page. New accounts get $5 in free credits (valid for 3 months).
Step 1: Register an OpenAI Account
- Go to platform.openai.com
- Click "Sign up"
- Register with email or Google account
- Complete email verification
Note: The OpenAI Platform account and ChatGPT account are separate. Even if you already have a ChatGPT Plus account, you still need to set up API payment separately on the Platform.
Step 2: Set Up Payment Method
- After logging in, go to Settings -> Billing
- Click "Add payment method"
- Enter credit card information
Important for users: Some credit cards may be declined. If you encounter payment failure:
- Try credit cards from other banks
- Use an international Visa/Mastercard
- Use CloudInsight's enterprise purchasing service to skip payment hassles
Step 3: Create an API Key
- Go to the API Keys page
- Click "Create new secret key"
- Enter a name (e.g., "My Test Key")
- Copy and save immediately -- this key is only shown once
Your API Key looks like this: sk-proj-abc123...xyz
Security reminders:
- Don't put the key in your code
- Don't upload to GitHub
- Don't share with anyone
- Set up usage limits

Python Environment Setup & SDK Installation
Answer-First: Installing the OpenAI Python SDK takes just one command. We recommend using environment variables for API Key setup and creating a virtual environment (venv) for package management.
Install the Python SDK
pip install openai
The latest 2026 SDK (v2.x) syntax is much cleaner than the old version. If you see tutorials online using openai.ChatCompletion.create(), that's the old syntax -- don't follow it.
Set Up the API Key
Method 1: Environment Variables (Recommended)
# macOS / Linux
export OPENAI_API_KEY="sk-proj-your-key-here"
# Windows PowerShell
$env:OPENAI_API_KEY="sk-proj-your-key-here"
Method 2: .env File
Create a .env file:
OPENAI_API_KEY=sk-proj-your-key-here
Load in Python:
from dotenv import load_dotenv
load_dotenv()
from openai import OpenAI
client = OpenAI() # Automatically reads environment variable
Create a Virtual Environment (Recommended)
python -m venv myenv
source myenv/bin/activate # macOS/Linux
pip install openai python-dotenv
Chat Completions API Complete Examples
Answer-First: The Chat Completions API is OpenAI's most core API. Call client.chat.completions.create() with a model name and conversation messages.
Basic Example: Ask a Question
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "Describe Taiwan's semiconductor industry in three sentences"}
]
)
print(response.choices[0].message.content)
Advanced Example: System Prompt + Multi-Turn Conversation
from openai import OpenAI
client = OpenAI()
messages = [
{"role": "system", "content": "You are a senior tech industry analyst. Answer in English."},
{"role": "user", "content": "What is TSMC's competitive moat?"},
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
temperature=0.7,
max_tokens=800
)
answer = response.choices[0].message.content
print(answer)
# Continue the conversation
messages.append({"role": "assistant", "content": answer})
messages.append({"role": "user", "content": "Can Samsung and Intel catch up?"})
response2 = client.chat.completions.create(
model="gpt-4o",
messages=messages,
temperature=0.7,
max_tokens=800
)
print(response2.choices[0].message.content)
Key Parameter Reference
| Parameter | Description | Recommended Value |
|---|---|---|
model | Select model | gpt-4o (primary), gpt-4o-mini (budget) |
temperature | Creativity level (0-2) | 0.3 (factual), 0.7 (general), 1.0 (creative) |
max_tokens | Maximum response length | Varies by need, typically 500-2000 |
top_p | Another way to control randomness | Usually don't adjust alongside temperature |
stream | Streaming output (real-time display) | True (for real-time response scenarios) |
Streaming Output
Make responses appear character by character like typing:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Tell me a short joke"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Purchase OpenAI API through CloudInsight for exclusive enterprise discounts and invoices. Learn more ->
API Playground Tutorial
Answer-First: OpenAI Playground is an official online testing interface. Without writing any code, you can test various models, adjust parameters, and preview API responses.
Where Is Playground?
Go to platform.openai.com/playground and log in to use it.
Playground Features
- Select models: Switch between GPT-5, GPT-4o, GPT-4o-mini in the top right
- Adjust parameters: Adjust temperature, max tokens, etc. in the right panel
- System Prompt: Set system instructions in the top left
- Chat testing: Type directly in the center area
- Export code: Click "View code" to get Python code after successful testing
Playground Usage Tips
- Test prompts in Playground first, then write them into code once confirmed
- Use Playground to compare different models and see which gives the best responses
- Use Playground to tune parameters and find the optimal temperature for your scenario
Want to learn more AI API basics? Check out AI API Beginner's Complete Guide.
Want to learn other AI APIs?
- Gemini Tutorial | Google Gemini API Integration Complete Guide
- Python AI API Tutorial | Complete Guide to Integrating Major AI APIs
More on OpenAI pricing and plans? Check out OpenAI API Pricing Explained.
Want a deep dive into OpenAI's models, features, and enterprise plans? Check out OpenAI API Complete Guide.
FAQ: OpenAI API Tutorial Common Questions
Does applying for an OpenAI API Key cost money?
Applying for an account and key is free. New accounts get $5 in free credits (valid for 3 months). After that, you need to top up to continue using it. The minimum top-up is $5.
What's the difference between OpenAI API and ChatGPT Plus?
ChatGPT Plus is a $20/month subscription service where you chat on a webpage. OpenAI API is a usage-based developer tool that lets you call GPT models with code. The accounts are separate, billing is separate. API is better suited for automation and product integration.
Can OpenAI API be used internationally?
Yes. However, some credit cards may be declined. Solutions: try a different bank's card, use an international card, or use CloudInsight enterprise purchasing (with invoices included).
Is using the API more expensive than ChatGPT Plus?
It depends on usage. If you only ask a few questions per day, ChatGPT Plus ($20/month) is more cost-effective. If you need to automate processing large volumes of tasks, the pay-per-use API can actually be cheaper. GPT-4o-mini's API cost is extremely low -- just $0.15 per million Input Tokens.
What are OpenAI API's Rate Limits?
It depends on your account tier. Free accounts typically allow 3 requests per minute. Paid accounts unlock higher limits based on cumulative spending. Tier 1 ($5+ spent) typically allows 500 requests per minute.
Get a Quote for OpenAI API Enterprise Plans
CloudInsight offers OpenAI API enterprise purchasing services:
- Enterprise-exclusive discounts, better than official pricing
- Invoices included, solving payment and expense reporting issues
- Technical support in your language, instant help with API usage questions
Get a quote for enterprise plans -> | Join LINE for instant consultation ->
References
- OpenAI Platform - Chat Completions API (2026)
- OpenAI - API Key Management Documentation
- OpenAI - Playground Documentation
- OpenAI - Rate Limits & Usage Tiers
- OpenAI Python SDK - GitHub Repository
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": "OpenAI API Tutorial | 2026 Complete Guide from API Key to Code Examples",
"author": {
"@type": "Person",
"name": "CloudInsight Technical Team",
"url": "https://cloudinsight.cc/about"
},
"datePublished": "2026-03-21",
"dateModified": "2026-03-21",
"publisher": {
"@type": "Organization",
"name": "CloudInsight",
"url": "https://cloudinsight.cc"
}
}
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "Does applying for an OpenAI API Key cost money?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Applying for an account and key is free. New accounts get $5 in free credits (valid for 3 months). After that, you need to top up to continue using it."
}
},
{
"@type": "Question",
"name": "What's the difference between OpenAI API and ChatGPT Plus?",
"acceptedAnswer": {
"@type": "Answer",
"text": "ChatGPT Plus is a $20/month web chat service. OpenAI API is a usage-based developer tool for calling models with code, ideal for automation and product integration."
}
},
{
"@type": "Question",
"name": "Can OpenAI API be used internationally?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Yes, but some credit cards may be declined. Try different bank cards, use an international card, or use CloudInsight enterprise purchasing."
}
},
{
"@type": "Question",
"name": "Is using the API more expensive than ChatGPT Plus?",
"acceptedAnswer": {
"@type": "Answer",
"text": "It depends on usage. For just a few daily questions, ChatGPT Plus is more cost-effective. For automated bulk processing, the pay-per-use API is cheaper. GPT-4o-mini costs just $0.15 per million Input Tokens."
}
},
{
"@type": "Question",
"name": "What are OpenAI API's Rate Limits?",
"acceptedAnswer": {
"@type": "Answer",
"text": "It depends on account tier. Free accounts typically allow 3 requests per minute. Tier 1 ($5+ spent) typically allows 500 requests per minute."
}
}
]
}
Need Professional Cloud Advice?
Whether you're evaluating cloud platforms, optimizing existing architecture, or looking for cost-saving solutions, we can help
Book Free ConsultationRelated Articles
AI API Tutorial | Learn to Integrate OpenAI, Claude, and Gemini APIs from Scratch in 2026
2026 AI API tutorial! From API fundamentals and integration guides to hands-on practice, learn step by step how to use OpenAI, Claude, and Gemini APIs.
AI APIGPT-5 Is Here! 2026 OpenAI API Complete Guide: Model Capabilities, Integration & Enterprise Applications
2026 GPT-5 and OpenAI API complete technical guide. From GPT-5 new features, API registration, token pricing to enterprise-grade integration — master the latest OpenAI development information and practical tutorials in one article.
AI APIGemini Tutorial | Complete Guide to Google Gemini API Integration & Usage in 2026
2026 Gemini tutorial! Google Gemini API integration steps, registration guide, Python code examples — get started with Gemini quickly through Google AI Studio.