All guides
OpenAI · Beginner
OpenAI API - first call, streaming, and cost control
Go from zero to a production feature with GPT-5 without blowing up the bill.
9 min readUpdated Jun 2026
1. Get the key
Create an account at platform.openai.com, go to API Keys -> Create new secret key. Add credit in Billing (minimum US$5). Store the key in an environment variable, never in the frontend.
2. First call (TypeScript)
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const res = await client.chat.completions.create({
model: "gpt-5-mini",
messages: [{ role: "user", content: "Explain RLHF in 2 sentences." }],
});
console.log(res.choices[0].message.content);3. Streaming
const stream = await client.chat.completions.create({
model: "gpt-5-mini",
messages: [{ role: "user", content: "Write a haiku about TypeScript" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}4. Structured outputs
const res = await client.chat.completions.create({
model: "gpt-5",
messages: [{ role: "user", content: "Extract name and email: Jane <jane@example.com>" }],
response_format: { type: "json_schema", json_schema: {
name: "Contact",
schema: { type: "object", required: ["name","email"],
properties: { name: {type:"string"}, email: {type:"string"} } },
strict: true,
}},
});5. Cost control
- •Use `gpt-5-mini` as the default; move to `gpt-5` only where reasoning quality matters
- •Enable prompt caching for 50-90% discounts on repeated prefixes
- •Truncate old history (keep the last N messages)
- •Rate-limit on your side so the monthly budget cannot spike