OpenAI API Examples: 7 Copy-Paste Snippets (2026)
Before you run any example
Every example below uses the Responses API (POST /v1/responses), which OpenAI's quickstart uses for all new code, and the official SDKs (pip install openai, npm install openai). Set your key once and the SDKs pick it up automatically:
export OPENAI_API_KEY="sk-..."If you do not have a key yet, see how to get an OpenAI API key. The model in these examples is gpt-6.2-sol, the lower-cost flagship on OpenAI's pricing page in November 2026; swap in gpt-6.2-astra for harder tasks or gpt-6-luna for cheap, simple ones. All snippets were checked against OpenAI's quickstart and function-calling guides on November 25, 2026.
|
Task |
Endpoint |
Key field |
|---|---|---|
|
Generate text |
|
|
|
Stream text |
|
|
|
Analyse an image or PDF |
|
|
|
Call your own function |
|
|
|
Return strict JSON |
|
|
|
Search the web |
|
|
|
Create embeddings |
|
|
Example 1: Generate text
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-sol",
instructions="You are a concise technical writer.",
input="Explain what an idempotency key is in two sentences.",
)
print(response.output_text)import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-sol",
input: "Explain what an idempotency key is in two sentences.",
});
console.log(response.output_text);curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{"model": "gpt-6.2-sol", "input": "Explain what an idempotency key is in two sentences."}'output_text is an SDK convenience that joins all text parts. With raw HTTP, read the output array: the assistant text is in an item of type message, inside content[].text.
Example 2: Stream the response
stream = client.responses.create(
model="gpt-6.2-sol",
input="Write a haiku about rate limits.",
stream=True,
)
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)Streaming returns typed server-sent events. Print the response.output_text.delta events for live text and wait for response.completed to get usage totals.
Example 3: Send an image or a PDF
response = client.responses.create(
model="gpt-6.2-sol",
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image?"},
{"type": "input_image", "image_url": "https://example.com/receipt.png"},
],
}],
)
print(response.output_text)For a PDF, use a content part of type input_file with a file_url, a file_id from the Files API, or base64 file_data. Which formats each part accepts is listed in OpenAI API supported file types.
Example 4: Function calling
The model does not run your code. It returns a function_call item; you run the function and send the result back as function_call_output:
import json
tools = [{
"type": "function",
"name": "get_order_status",
"description": "Look up the shipping status of an order.",
"strict": True,
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
"additionalProperties": False,
},
}]
history = [{"role": "user", "content": "Where is order A-1042?"}]
response = client.responses.create(model="gpt-6.2-sol", tools=tools, input=history)
history += response.output
for item in response.output:
if item.type == "function_call" and item.name == "get_order_status":
args = json.loads(item.arguments)
result = {"order_id": args["order_id"], "status": "shipped"} # your real lookup
history.append({"type": "function_call_output", "call_id": item.call_id,
"output": json.dumps(result)})
final = client.responses.create(model="gpt-6.2-sol", tools=tools, input=history)
print(final.output_text)Two details from OpenAI's function-calling guide matter here: keep strict: True with additionalProperties: False so arguments always match the schema, and pass the whole response.output back, because reasoning models need their reasoning items returned alongside the tool results.
Example 5: Structured JSON output
import json
response = client.responses.create(
model="gpt-6.2-sol",
input="Extract the company and amount: 'Invoice from Acme Ltd for $1,250.'",
text={"format": {
"type": "json_schema",
"name": "invoice",
"strict": True,
"schema": {
"type": "object",
"properties": {"company": {"type": "string"}, "amount": {"type": "number"}},
"required": ["company", "amount"],
"additionalProperties": False,
},
}},
)
print(json.loads(response.output_text))With strict set, the output is constrained to the schema, which is more reliable than asking for JSON in the prompt. The Python SDK also offers client.responses.parse() with a Pydantic model if you prefer typed objects.
Example 6: Built-in web search
response = client.responses.create(
model="gpt-6.2-sol",
tools=[{"type": "web_search"}],
input="What changed in the latest Node.js LTS release?",
)
print(response.output_text)Web search is billed per call ($10 per 1,000 calls on the November 2026 pricing page) plus the search content tokens at the model's rates, so do not enable it on every request by default.
Example 7: Embeddings
emb = client.embeddings.create(
model="text-embedding-3-small",
input=["refund policy for annual plans", "how to cancel a subscription"],
)
vectors = [d.embedding for d in emb.data]
print(len(vectors), len(vectors[0]))text-embedding-3-small costs $0.02 per million tokens and is enough for most search and clustering jobs; text-embedding-3-large costs $0.13.
Running the same examples against another provider
Every example uses the official SDK, so it also runs against an OpenAI-compatible gateway or a self-hosted server by changing two settings:
client = OpenAI(base_url="https://your-gateway.example.com/v1", api_key="YOUR_GATEWAY_KEY")The catch is that many compatible servers implement only /v1/chat/completions, not /v1/responses. For those, use client.chat.completions.create(model=..., messages=[...]) instead. Which features carry over is covered in what an OpenAI-compatible API is, and the same calls for Claude are in our Claude API curl examples.
FAQ
Where can I find official OpenAI API examples?
OpenAI's developer quickstart and guides at developers.openai.com include Python, JavaScript, curl and other SDK snippets, and the OpenAI Cookbook on GitHub has longer notebook examples. The snippets on this page follow those guides.
Should new code use the Responses API or Chat Completions?
Use the Responses API. OpenAI's quickstart and tool guides are written for it, and built-in tools such as web search and file search run through it. Chat Completions remains useful mainly for OpenAI-compatible servers that do not support /v1/responses.
What is the simplest OpenAI API example?
A single client.responses.create(model="gpt-6.2-sol", input="...") call followed by print(response.output_text), with your key in the OPENAI_API_KEY environment variable.
Why does my example return a 401 or 429 error?
A 401 means the key is missing, wrong or revoked. A 429 means you hit a rate limit or your project has no remaining credit; check billing and usage limits in the dashboard, then retry with backoff.
Do these examples work with Node.js and TypeScript?
Yes. The openai npm package exposes the same client.responses.create method and output_text property; save the file as .mts or use ES modules for top-level await.
The short version
Install the SDK, set OPENAI_API_KEY, and start from client.responses.create. Add stream=True for live output, content parts for images and PDFs, tools for function calling or web search, and text.format with a strict schema for JSON. Before you scale any of these, check what the calls will cost in our OpenAI API pricing breakdown.