Tutorials14 min read

How to Use the ChatGPT API: Complete Beginner's Guide

A step-by-step guide to using the OpenAI API. Learn to make your first API call, manage tokens, stream responses, and build your first AI application.

Taylor Nguyen

Senior Software Engineer

Advertisement

article-top

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

  1. Go to platform.openai.com and create an account
  2. Navigate to API Keys in your account settings
  3. Click "Create new secret key" and copy it immediately (you won't see it again)
  4. 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_tokens to 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

#OpenAI#API#tutorial#Python#beginners

Advertisement

article-mid

๐Ÿ“ง

Stay Ahead of the AI Curve

Get the best AI tools, prompts, and tutorials delivered to your inbox every week. Join 25,000+ readers who stay smart about AI.

No spam. Unsubscribe anytime. 100% free.