Back to HomeAI API

OpenAI API Tutorial | 2026 Complete Guide from API Key to Code Examples

9 min min read
#OpenAI API#GPT-4o#API Key#Python#API Tutorial#Chat Completions#Playground#Code Examples#Beginner Guide#AI Development

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

  1. Go to platform.openai.com
  2. Click "Sign up"
  3. Register with email or Google account
  4. 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

  1. After logging in, go to Settings -> Billing
  2. Click "Add payment method"
  3. Enter credit card information

Important for users: Some credit cards may be declined. If you encounter payment failure:

Step 3: Create an API Key

  1. Go to the API Keys page
  2. Click "Create new secret key"
  3. Enter a name (e.g., "My Test Key")
  4. 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

OpenAI API Tutorial Steps


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

ParameterDescriptionRecommended Value
modelSelect modelgpt-4o (primary), gpt-4o-mini (budget)
temperatureCreativity level (0-2)0.3 (factual), 0.7 (general), 1.0 (creative)
max_tokensMaximum response lengthVaries by need, typically 500-2000
top_pAnother way to control randomnessUsually don't adjust alongside temperature
streamStreaming 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

  1. Test prompts in Playground first, then write them into code once confirmed
  2. Use Playground to compare different models and see which gives the best responses
  3. 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?

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

  1. OpenAI Platform - Chat Completions API (2026)
  2. OpenAI - API Key Management Documentation
  3. OpenAI - Playground Documentation
  4. OpenAI - Rate Limits & Usage Tiers
  5. 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 Consultation

Related Articles