Skip to content

OpenAI API Quickstart

Last updated:2026-08-12· 16 min read

🚀 Quick access

  • ChatGPT Domestic:Open entry↗
  • Mirror site:Open mirror↗
  • Official ChatGPT:chatgpt.com ↗

OpenAI API Quickstart

Last updated: 2026-08-12

Overview

The OpenAI API lets you embed GPT-family models in websites, scripts, support bots, and internal tools. This guide goes from Platform account to first HTTP request—key management, Responses / Chat Completions examples, SDK calls, common errors, and pre-launch security. Endpoints, model IDs, and field names follow official Quickstart—OpenAI may prioritize Responses while keeping Chat Completions for legacy code.

How is the API different from ChatGPT web?

Dimensionchatgpt.comOpenAI API
UsageBrowser chatHTTP / official SDK
BillingChatGPT subscriptionPer token usage
IntegrationHuman interactionEmbeddable product flows
SecretAccount loginAPI key (must stay private)

Choice: human chat → web; automation, batch jobs, product features → API.

Set up account and API key

  1. Sign in to OpenAI Platform.
  2. Create a key under API keys; copy immediately—the page may not show it again.
  3. Label the key (e.g. dev-bot / prod-summarizer) for rotation after leaks.
  4. Enable billing and usage/budget alerts in Billing (if offered).
# Linux / macOS
export OPENAI_API_KEY="sk-..."

# Windows PowerShell
$env:OPENAI_API_KEY="sk-..."

Console regions: Platform Overview.

Your first API call

Examples show request shape; gpt-4o-mini and similar IDs are examples—replace after checking docs.

Responses API (check Quickstart for new projects)

curl https://api.openai.com/v1/responses \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini",
    "input": "Explain RAG in three sentences"
  }'

Chat Completions (common in tutorials and legacy code)

curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [
      {"role": "system", "content": "You are a concise technical assistant."},
      {"role": "user", "content": "Explain RAG in three sentences"}
    ]
  }'

Python SDK example

# pip install openai  # version per official docs
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY

resp = client.chat.completions.create(
    model="gpt-4o-mini",  # example ID—check docs
    messages=[{"role": "user", "content": "Explain RAG in three sentences"}],
)
print(resp.choices[0].message.content)
print(resp.usage)

Node.js SDK example

// npm install openai  // version per official docs
import OpenAI from "openai";

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const resp = await client.chat.completions.create({
  model: "gpt-4o-mini", // example ID—check docs
  messages: [{ role: "user", content: "Explain RAG in three sentences" }],
});
console.log(resp.choices[0].message.content);
console.log(resp.usage);

If the SDK exposes client.responses.create(...), follow Quickstart to choose Completions or Responses.

Read responses and usage

Successful responses include generated text and usage (prompt / completion tokens). Log from day one:

FieldUse
usage.prompt_tokensInput cost
usage.completion_tokensOutput cost
Response id or header x-request-idSupport tickets

Pricing: openai.com/api/pricing

How to choose a model

ScenarioLean towardValidate with
Short support repliesSmaller/faster tierP95 latency, satisfaction
Long document summaryLong-context modelMissed-fact spot checks
Complex reasoningStronger tierSample-set accuracy
High-QPS batchCost-optimized tierBill + rate limits

Compare two model IDs on the same real inputs before setting defaults. Details: Text Generation guide.

Billing, rate limits, and monitoring

  • Tokens: input and output both bill; system and retrieval context count as input.
  • Rate limits: on 429, backoff—don’t max concurrency.
  • Monitoring: log model, latency, tokens, HTTP status; alert on 5xx/429.

Common HTTP errors

StatusCommon meaningAction
401Invalid or missing keyCheck Authorization and env vars
429Rate limitedExponential backoff; raise quota or lower QPS
400Bad request bodyVerify model / messages in API reference
500+Server errorLimited retry + status.openai.com

Security checklist (before launch)

  • Key only in server env vars or secret manager
  • Never in frontend, mobile app, or public GitHub
  • Length limits and PII filtering on user input (per compliance)
  • Redact logs: no full passwords, card numbers, health data
  • Rotate keys regularly; revoke on offboarding
  • Different keys for dev / staging / prod

Copy-ready system + user template

[System]
You are an enterprise knowledge assistant. Answer only from provided context.
If context is insufficient, say "Not mentioned in the materials" and list what's missing.
Do not invent links or legal citations.

[User]
context:
"""
[paste redacted passage]
"""
Question: [user question]

Systematic prompts: Prompt Engineering guide.

Frequently asked questions

What if my API key leaked?

Revoke it immediately on Platform, create a new key, and audit Git history, CI logs, and frontend bundles.

Does ChatGPT Plus include API quota?

No. API bills separately on Platform.

Responses or Chat Completions?

Follow Quickstart. New projects follow official recommendation; legacy projects read migration notes—see API Developer Guide and Responses API Guide.

Can servers in restricted regions call the API?

Depends on network and account region policy. API runs server-side, not in the browser; check official compliance and payment guidance.

Can I share one abstraction layer with Claude API?

Fields differ—adapt per vendor. A gateway can unify externally while serializing per docs. Compare: Claude API Get Started.

Official resources

Next reading

Action path

Today: Run one API call in a test environment and print usage. Tomorrow: Move the key to env vars; remove plaintext from code. This week: Build a 10-question benchmark, pick default model, then follow the production checklist.

Related