Comparisons Use Cases Research Papers Alternatives Glossary RAG Benchmarks
API Examples

OpenAI API Examples

APIOpenAI

Real, working code examples for calling the OpenAI API, covering the most common patterns you'll need.

Basic Chat Completion (Python)

from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY")

response = client.chat.completions.create(
    model="gpt-5",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain what a context window is in one paragraph."}
    ]
)
print(response.choices[0].message.content)

Streaming a Response

stream = client.chat.completions.create(
    model="gpt-5",
    messages=[{"role": "user", "content": "Write a short poem about the ocean."}],
    stream=True
)
for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

JavaScript / Node.js Example

import OpenAI from "openai";
const client = new OpenAI({ apiKey: "YOUR_API_KEY" });

const response = await client.chat.completions.create({
  model: "gpt-5",
  messages: [{ role: "user", content: "Summarize this in two sentences: ..." }],
});
console.log(response.choices[0].message.content);

Common Parameters Worth Knowing

temperature controls randomness (lower is more focused and deterministic); max_tokens caps the length of the generated response; messages is the conversation history, including an optional system message that shapes overall behavior. See OpenAI's own current documentation for the complete, up-to-date parameter list and model names.

Frequently Asked

Is the model name in these examples always current?

Model names and versions change over time; check OpenAI's current documentation for the latest available model identifiers before deploying.

Do I need the official SDK to use these examples?

The official Python and JavaScript SDKs simplify usage significantly, as shown here; you can also call the API directly with raw HTTP requests if you prefer not to use an SDK.

Where do I get an API key?

Through your account on OpenAI's own platform; never commit a real API key to public source code or version control.

Where can I see similar examples for other providers?

See our Claude API Examples and Gemini API Examples pages for equivalent code in other major providers.

Chat with us+91 88401 46999