How to Use the OpenAI API: Keys, First Request, Streaming and Cost Control

Published October 21, 2026 · Last updated October 21, 2026

How to Use the OpenAI API: Keys, First Request, Streaming and Cost Control
Photo by Alejandro Escamilla (Unsplash)
Some links on this page are affiliate links. If you buy through them, we may earn a commission at no extra cost to you. This never influences our rankings or opinions.

The OpenAI API is still the reference integration: every tool ecosystem speaks it, and most providers (including local servers like LM Studio) emulate it. This guide gets you from an empty account to a working, budgeted integration.

Step 1: Get your API key

  1. Sign in at https://platform.openai.com (a regular ChatGPT account is a different thing; API usage is billed separately).
  2. Add a payment method under Billing — API access needs prepaid or postpaid billing.
  3. Go to API keys → Create new secret key, name it (e.g. myapp-dev), copy it once and store it safely. You won’t see it again.
  4. Set a monthly spending limit under Billing → Limits. Do this before you write any code; runaway scripts are the classic way people get surprise bills.

Step 2: Keep the key out of your code

Never hardcode the key. Use an environment variable:

# macOS / Linux
export OPENAI_API_KEY="sk-..."
echo 'export OPENAI_API_KEY="sk-..."' >> ~/.zshrc   # persist
# Windows PowerShell (persisted)
[Environment]::SetEnvironmentVariable("OPENAI_API_KEY", "sk-...", "User")

On Linux servers, a .env file with strict permissions works well too:

echo 'OPENAI_API_KEY=sk-...' > .env
chmod 600 .env

And .env must be in your .gitignore — leaked keys get scraped from public repos within minutes.

Step 3: First request in Python

python3 -m venv .venv && source .venv/bin/activate
pip install openai
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY automatically

resp = client.chat.completions.create(
    model="gpt-6.1-sol",
    messages=[
        {"role": "system", "content": "You are a concise technical writer."},
        {"role": "user", "content": "Explain what an API is in two sentences."},
    ],
)
print(resp.choices[0].message.content)
print("usage:", resp.usage)  # tokens -> check cost

Screenshot: the script installed and answering, with token usage

If your account doesn’t have the newest model enabled yet, gpt-5.1 works with identical code — just swap the model string.

Step 4: First request in Node.js

npm install openai
import OpenAI from "openai";

const client = new OpenAI(); // reads OPENAI_API_KEY

const resp = await client.chat.completions.create({
  model: "gpt-6.1-sol",
  messages: [{ role: "user", content: "Explain what an API is in two sentences." }],
});
console.log(resp.choices[0].message.content);

Step 5: Streaming (what users expect)

stream = client.chat.completions.create(
    model="gpt-6.1-sol",
    messages=[{"role": "user", "content": "Write a haiku about APIs."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

Step 6: Understand the cost model

Prices per million tokens (checked November 2026 — verify current rates on the pricing page):

ModelInputOutputBest for
GPT-6.2 Astra$8$40hardest reasoning tasks
GPT-6.2 Sol$2$10default workhorse
GPT-6 Luna$0.10$0.50high-volume, simple tasks

Rules of thumb:

Step 7: Error handling that won’t page you at 3 AM

import time
from openai import OpenAI, RateLimitError, APIConnectionError

def ask(prompt: str, retries: int = 3):
    for attempt in range(retries):
        try:
            return client.chat.completions.create(
                model="gpt-6.1-sol",
                messages=[{"role": "user", "content": prompt}],
            )
        except RateLimitError:
            time.sleep(2 ** attempt * 5)   # exponential backoff
        except APIConnectionError:
            time.sleep(2 ** attempt * 10)
    raise RuntimeError("API unavailable after retries")

Handle at minimum: RateLimitError (backoff), APIConnectionError (retry), and timeouts (set timeout=60 on the client for long generations).

Common pitfalls

Next steps