Development

How to Use OpenAI's API: Beginner Tutorial

Updated 2026-03-10

How to Use OpenAI’s API: Beginner Tutorial

The OpenAI API gives you programmatic access to GPT-4o, o3, DALL-E, and other models. This tutorial walks you through setup, your first API call, and common patterns. You will be up and running in 15 minutes.

AI model comparisons are based on publicly available benchmarks and editorial testing. Results may vary by use case.

Prerequisites

  • A computer with internet access
  • Basic familiarity with the command line or Python
  • A credit card for billing (pay-as-you-go)

Step 1: Create an OpenAI Account

  1. Go to platform.openai.com
  2. Sign up for an account
  3. Add a payment method
  4. Set a usage limit to avoid unexpected bills

Step 2: Get Your API Key

  1. Navigate to “API Keys” in your account settings
  2. Click “Create new secret key”
  3. Copy and store the key securely

Security note: Store your API key as an environment variable. Never commit it to code repositories.

export OPENAI_API_KEY="your-key-here"

Step 3: Install the SDK

Python

pip install openai

TypeScript/JavaScript

npm install openai

Step 4: Make Your First API Call

Python

from openai import OpenAI

client = OpenAI()  # Uses OPENAI_API_KEY env variable

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "What is the capital of France?"}
    ]
)

print(response.choices[0].message.content)

TypeScript

import OpenAI from 'openai';

const client = new OpenAI();  // Uses OPENAI_API_KEY env variable

const response = await client.chat.completions.create({
    model: "gpt-4o",
    messages: [
        { role: "user", content: "What is the capital of France?" }
    ]
});

console.log(response.choices[0].message.content);

cURL

curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "What is the capital of France?"}
    ]
  }'

Step 5: Add a System Message

System messages define the AI’s behavior:

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful data analyst. Be concise and use bullet points."},
        {"role": "user", "content": "Analyze this sales data: Q1: $500K, Q2: $620K, Q3: $580K, Q4: $710K"}
    ]
)

Prompt Engineering 101: Get Better Results from Any AI

Step 6: Enable Streaming

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "Write a short poem about programming."}
    ],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

Available Models

ModelBest ForPrice (input/output per 1M)
gpt-4oGeneral purpose, multimodal$2.50 / $10.00
gpt-4o-miniBudget, fast$0.15 / $0.60
o3Hard reasoning, math$10.00 / $40.00
o3-miniBudget reasoning$1.10 / $4.40

AI API Pricing Comparison: Cost Per Million Tokens

Key Parameters

ParameterPurposeValues
modelWhich modelgpt-4o, gpt-4o-mini, o3
max_tokensMax output length1024 for short, 4096 for long
temperatureCreativity0.0 (focused) to 1.0 (creative)
response_formatOutput format{"type": "json_object"} for JSON
streamReal-time outputtrue / false

Common Patterns

Image Generation (DALL-E 3)

response = client.images.generate(
    model="dall-e-3",
    prompt="A serene mountain landscape at sunset, photorealistic",
    size="1024x1024",
    quality="standard",
    n=1
)

image_url = response.data[0].url

Vision (Image Understanding)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What is in this image?"},
            {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
        ]
    }]
)

Function Calling

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What's the weather in Paris?"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"}
                },
                "required": ["location"]
            }
        }
    }]
)

Error Handling

from openai import OpenAI, RateLimitError, APIError

try:
    response = client.chat.completions.create(...)
except RateLimitError:
    print("Rate limited. Wait and retry.")
except APIError as e:
    print(f"API error: {e}")

Key Takeaways

  • The OpenAI API provides access to GPT-4o, o3, DALL-E, and other models via simple REST calls.
  • Start with GPT-4o for general tasks and gpt-4o-mini for budget-friendly applications.
  • System messages control the AI’s behavior and are the highest-leverage configuration point.
  • Function calling enables AI to interact with external tools and APIs.
  • Set usage limits in your account to avoid unexpected bills.

Next Steps


This content is for informational purposes only and reflects independently researched comparisons. AI model capabilities change frequently — verify current specs with providers. Not professional advice.