How to Use the OpenAI API: Keys, First Request, Streaming and Cost Control
Published October 21, 2026 · Last updated October 21, 2026
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
- Sign in at https://platform.openai.com (a regular ChatGPT account is a different thing; API usage is billed separately).
- Add a payment method under Billing — API access needs prepaid or postpaid billing.
- 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. - 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

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):
| Model | Input | Output | Best for |
|---|---|---|---|
| GPT-6.2 Astra | $8 | $40 | hardest reasoning tasks |
| GPT-6.2 Sol | $2 | $10 | default workhorse |
| GPT-6 Luna | $0.10 | $0.50 | high-volume, simple tasks |
Rules of thumb:
- Output tokens cost 5x input on most tiers. Verbose outputs are the expensive part.
- Cache saves money: repeated prefixes (system prompts, docs) cost a fraction on cache hits. Keep your system prompt stable.
- Estimate before scaling: log
resp.usagein development for a week to see real per-request costs before you launch anything user-facing.
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
- 429 errors with a funded account: you’re hitting requests-per-minute tier limits; they rise with usage history. Backoff properly instead of hammering.
- Wrong model name: model IDs are exact strings (
gpt-6.1-sol); typos give a confusing 404. - Tokens ≠ words: English is roughly 4 characters per token; Spanish/French are closer to 3-4; code varies wildly. Budget accordingly.
- Forgetting max_tokens on long generations: responses truncate mid-word. Set it
generously and check
finish_reasonfor"length".
Next steps
- Compare providers with our model comparison — DeepSeek and Gemini undercut OpenAI on price for many workloads.
- Point any OpenAI-compatible client at local models instead — zero API cost.
- For agentic coding use cases, the OpenCode guide shows a provider-agnostic setup.