Explain it simply
Explain it simply
The Responses API is the one endpoint where you send what you want the model to do and receive what the model did. What the model did comes back as a list of items: perhaps a short reasoning item, a message that holds the text, and, when you enable tools, tool calls.
Think of a kitchen ticket system. You hand in an order slip, which is your input. The kitchen returns a tray with several things on it, such as a note, the dish and maybe a receipt. Your job is to pick the dish off the tray by what it is, not to grab whatever happens to lie on top.
Problem → Why → Solution
The problem: the wrong path and a retry storm
A tutorial shows data.choices[0].message.content. You paste it after a call to the Responses endpoint and get a TypeError, because that path belongs to the older chat completions shape. You switch to data.output[0].content[0].text. It works in testing, then prints undefined the day the first output item is a reasoning item or the message holds a refusal instead of text.
Meanwhile the key sits in a constant that is bundled into the web app, and a loop retries every failure, including a 429 caused by an empty credit balance. The loop never succeeds, the account never recovers and the logs fill with identical errors.
// OPENAI_KEY is bundled into the web app, so every visitor can read it
const res = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: { Authorization: "Bearer " + OPENAI_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ model: "gpt-old-tutorial", input: "Give 3 REST tips" }),
});
const data = await res.json();
console.log(data.choices[0].message.content); // chat completions path: no such field
console.log(data.output[0].content[0].text); // first item is not always a messageWhy a 200 is not the end of the story
The endpoint returns a typed list, not one string, and its errors carry a type and a code that separate fixable situations from permanent ones. Code that ignores both will either crash on a valid reply or keep retrying something that cannot succeed. Reading by item type and deciding by error code removes both failure modes.
Core concept: a request, a list of items and two kinds of 429
The facts here come from OpenAI's API documentation. Model ids change often, so the lesson uses <model-id> and tells you to read the current model list.
1. Endpoint and authorization
Send POST to https://api.openai.com/v1/responses with the header Authorization: Bearer $OPENAI_API_KEY and Content-Type: application/json. The official SDKs read OPENAI_API_KEY from the environment automatically, so the key never has to appear in your source.
2. The request body
A normal request sends model and input. input can be a plain string or an array of role-tagged messages, where developer messages written by your application outrank user messages. instructions sets high-level behaviour for that one request, previous_response_id chains turns together, and stream: true asks for events instead of one JSON reply.
3. Output is an array of typed items
The response has an id, a status, usage and an output array. A message item holds content parts, while reasoning items or tool calls can sit before or after it. The docs warn that it is not safe to assume the text is at output[0].content[0].text. The SDK property output_text joins all text for you, but code that uses raw HTTP has to walk the array itself.
4. Text or refusal
Inside a message, a content part is either output_text, with the text in a text field, or a refusal part when the model declines. A reply with HTTP 200 can therefore contain no output_text at all, and your code should treat that as a normal outcome.
5. Limits and headers
Limits are expressed in requests and tokens per minute, per day and in other units. Responses carry x-ratelimit-remaining-requests, x-ratelimit-remaining-tokens and matching reset headers whose values are durations such as 1s or 6m0s. A 429 or 503 may also include Retry-After, the minimum number of seconds to wait.
6. Two kinds of 429
A rate limit, for example error type rate_limit_error with code slow_down, clears when you slow down and obey Retry-After. A billing or spend limit, for example credit_balance_exhausted or organization_spend_limit_exceeded, often under the broader type insufficient_quota, never clears by waiting. Retrying cannot restore access until credits or limits change.
| Status / code | Meaning | Action |
|---|---|---|
| 401 | Wrong or missing key | Stop, fix the key |
| 403 | Region not supported | Stop, not a code bug |
| 429 slow_down | Rate rose too fast | Wait Retry-After, retry |
| 429 credit_balance_exhausted | No prepaid credit | Stop, add credit |
| 500 | Server issue | Retry briefly |
| 503 server_is_overloaded | Model overloaded | Follow Retry-After, retry |
- Bearer key proves who you are
- Send model and input
- Walk output items by type
- error.type and code pick the action
Never index into output by position. Filter by type, and let the error code, not the HTTP number alone, choose between retry and stop.
General pattern
curl https://api.openai.com/v1/responses \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "<model-id>",
"input": "<prompt>"
}'Replace <model-id> with an id from OpenAI's current model list and <prompt> with your text. The command is illustrative: check the current docs, and use your own key from an environment variable rather than typing it into the command.
Walking the output array, with refusals and errors
The mock server returns a reasoning item followed by a message item, and it can also answer with a refusal or with each of the error situations from the table. The client keeps the model id in an environment variable, reads the text by item type, prints the rate-limit headers and then runs four failing calls through a small decide() function.
import http from "node:http";
const KEY = "sk-demo-openai-key";
// Mock server: same SHAPE as POST /v1/responses, no network and no real key.
const server = http.createServer((req, res) => {
let raw = "";
req.on("data", (chunk) => (raw += chunk));
req.on("end", () => {
const send = (status, body, headers = {}) => {
res.writeHead(status, { "content-type": "application/json", ...headers });
res.end(JSON.stringify(body));
};
const fail = (status, type, code, message) =>
send(status, { error: { message, type, param: null, code } });
const message = (content) => ({
type: "message",
id: "msg_demo",
status: "completed",
role: "assistant",
content,
});
if (req.headers.authorization !== "Bearer " + KEY) {
return fail(401, "invalid_request_error", "invalid_api_key", "Incorrect API key");
}
const body = JSON.parse(raw);
if (body.input === "slow") {
return fail(429, "rate_limit_error", "slow_down", "Request rate rose too fast");
}
if (body.input === "broke") {
return fail(429, "insufficient_quota", "credit_balance_exhausted", "No credits");
}
if (body.input === "busy") {
return fail(503, "service_unavailable_error", "server_is_overloaded", "Overloaded");
}
const tips = "1) Use nouns. 2) Return 201. 3) Version early.";
const content =
body.input === "refuse"
? [{ type: "refusal", refusal: "I cannot help with that." }]
: [{ type: "output_text", text: tips, annotations: [] }];
send(
200,
{
id: "resp_demo",
object: "response",
status: "completed",
model: body.model,
output: [{ type: "reasoning", id: "rs_demo", summary: [] }, message(content)],
usage: { input_tokens: 15, output_tokens: 42, total_tokens: 57 },
error: null,
incomplete_details: null,
},
{ "x-ratelimit-remaining-requests": "59", "x-ratelimit-reset-requests": "1s" },
);
});
});
async function askOpenAI(base, key, input) {
const res = await fetch(base + "/v1/responses", {
method: "POST",
headers: { authorization: "Bearer " + key, "content-type": "application/json" },
body: JSON.stringify({ model: process.env.OPENAI_MODEL ?? "model-from-env", input }),
});
const data = await res.json();
if (!res.ok) {
const { type, code, message } = data.error;
throw Object.assign(new Error(message), { status: res.status, type, code });
}
return { data, headers: res.headers };
}
// output is an array of items: keep messages, then keep their output_text parts.
function readOutput(response) {
const parts = response.output
.filter((item) => item.type === "message")
.flatMap((item) => item.content);
return {
text: parts.filter((part) => part.type === "output_text").map((p) => p.text).join(""),
refusal: parts.find((part) => part.type === "refusal")?.refusal ?? null,
};
}
function decide(err) {
if (err.status === 429 && err.type === "insufficient_quota") return "stop: fix billing";
if (err.status === 429 || err.status >= 500) return "retry with backoff";
return "stop: fix the request or key";
}
await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;
const { data, headers } = await askOpenAI(base, KEY, "Give 3 REST tips");
console.log("text:", readOutput(data).text);
console.log("item types:", data.output.map((item) => item.type).join(", "));
console.log("usage: in=" + data.usage.input_tokens, "out=" + data.usage.output_tokens);
console.log("requests left:", headers.get("x-ratelimit-remaining-requests"),
"(resets in " + headers.get("x-ratelimit-reset-requests") + ")");
const refused = await askOpenAI(base, KEY, "refuse");
console.log("refusal:", readOutput(refused.data).refusal);
const attempts = [["sk-wrong", "hi"], [KEY, "slow"], [KEY, "broke"], [KEY, "busy"]];
for (const [key, input] of attempts) {
try {
await askOpenAI(base, key, input);
} catch (err) {
console.log(err.status, err.type + "/" + err.code, "->", decide(err));
}
}
server.close();Code breakdown
- Bearer header
headers: { authorization: "Bearer " + key, "content-type": "application/json" },The key travels as a Bearer token. The mock compares it with its expected value and answers 401 for anything else, as the real endpoint does for a wrong key.
- Keep type and code
const { type, code, message } = data.error;All three fields are copied onto the thrown Error so decide() can separate a rate limit from a billing problem later.
- Messages first
.filter((item) => item.type === "message")The reasoning item is skipped here. The output prints reasoning, message, which is exactly why a fixed index would be wrong.
- A refusal is data
refusal: parts.find((part) => part.type === "refusal")?.refusal ?? null,A declined request is still HTTP 200. The function returns the refusal text separately, so the caller can show a polite message instead of an empty string.
- Two kinds of 429
if (err.status === 429 && err.type === "insufficient_quota") return "stop: fix billing";The same status leads to opposite actions. slow_down is retried; credit_balance_exhausted stops the loop because waiting cannot help.
- Read the headroom
headers.get("x-ratelimit-remaining-requests")Headers are available on every response, not only on errors. Logging them shows how close you are to a limit before the 429 arrives.
text: 1) Use nouns. 2) Return 201. 3) Version early.
item types: reasoning, message
usage: in=15 out=42
requests left: 59 (resets in 1s)
refusal: I cannot help with that.
401 invalid_request_error/invalid_api_key -> stop: fix the request or key
429 rate_limit_error/slow_down -> retry with backoff
429 insufficient_quota/credit_balance_exhausted -> stop: fix billing
503 service_unavailable_error/server_is_overloaded -> retry with backoffThe same call in curl
This command is illustrative: check the current docs, export your own key as OPENAI_API_KEY and set OPENAI_MODEL to an id from the model list. The jq filter walks the same path as the Node code: message items, then their content parts.
# Illustrative - check the current docs, and use your own key in OPENAI_API_KEY.
curl https://api.openai.com/v1/responses \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d "{
\"model\": \"$OPENAI_MODEL\",
\"input\": \"Give 3 REST tips in one line each\"
}" | jq -r '.output[] | select(.type == "message") | .content[] | .text'Responses and chat completions side by side
Older tutorials, and many OpenAI-compatible services such as Hugging Face's router, use the chat completions shape. Knowing both lets you read any example you meet.
| Responses | Chat completions | |
|---|---|---|
| Path | /v1/responses | /v1/chat/completions |
| Prompt field | input | messages |
| Text lives in | output[] message items, content[] output_text | choices[0].message.content |
| Usage fields | input_tokens, output_tokens | prompt_tokens, completion_tokens |
Streaming and cost control
Set stream: true and the server sends semantic events instead of one JSON document. The ones you need first are response.created, response.output_text.delta, whose delta field holds the next piece of text, response.completed and error. Branch on event.type and ignore types you do not know.
- Keep the key in server-side secret storage and put per-user authorization, a budget and a rate limit in front of the model call.
- Set spend limits in your OpenAI account settings so a bug cannot run up an unbounded bill.
- Validate model output and any tool arguments as untrusted data before acting on them.
In real projects
How to apply it in a real project
Suppose your support tool drafts replies for human agents. Put the OpenAI call in a server adapter. The adapter reads the model id from OPENAI_MODEL, assembles input from your own templates, limits the output length, and refuses to run for a visitor who is not signed in. After each call it logs the status, the usage numbers and any request id the API returns.
The adapter parses structured output as JSON and validates it before the UI sees it, and the draft is shown to an agent instead of being sent automatically. Its tests use a mock server that returns a 400, a slow_down 429, a credit_balance_exhausted 429, a 500 and a stalled response, so every branch of the retry logic runs before launch.
Common mistakes
Common mistakes
Four slips cause most OpenAI integration trouble.
Pasting the chat completions path into a Responses call
choices[0].message.content does not exist in a Responses reply. Read output items by type, or use the SDK's output_text helper when you have an SDK.
Treating every 429 the same
A slow_down 429 is worth retrying after Retry-After. A credit_balance_exhausted or spend-limit 429 is not, because waiting cannot add credit. Branch on error.type and error.code.
Assuming HTTP 200 means there is text
A message can hold a refusal part, and a response can report an incomplete status with incomplete_details. Check for both before you display the answer.
Shipping the key in a front end
Anything bundled into a web or mobile app can be extracted, and then someone else spends your money. Keep the key on a server and authorize each user there.
Best practices
Habits worth keeping
- Pin the model id in configuration, and run your tests against a staging key whenever you change it.
- Cap attempts and total retry time, add a little random delay, and honour Retry-After when it is present.
- Log status, usage and request ids, and keep prompts and keys out of the logs.
Mini challenge
Read the rate-limit headers
Write toMs(text), which converts duration strings such as 1s, 6m0s and 20ms into milliseconds, and readLimits(headers), which returns the remaining requests, the remaining tokens and the token reset time in milliseconds. Prove it with a mock server on port 0 that answers two calls with different headers, and pause when fewer than 1000 tokens remain.
- Add up every number-and-unit pair, with the units ms, s, m and h
- Read x-ratelimit-remaining-requests and x-ratelimit-remaining-tokens as numbers
- Print pause plus the wait in milliseconds when fewer than 1000 tokens remain
- Close the mock server when the loop ends
import http from "node:http";
// Header values such as "1s", "6m0s" or "20ms" are durations, not numbers.
function toMs(text) {
// TODO 1: add up every <number><unit> pair in the text, with the units
// ms, s, m and h, and return the total in milliseconds
return 0;
}
function readLimits(headers) {
// TODO 2: return { requestsLeft, tokensLeft, tokensResetMs } built from
// x-ratelimit-remaining-requests, x-ratelimit-remaining-tokens and
// x-ratelimit-reset-tokens (a header can be missing, so default sensibly)
return {};
}
// TODO 3: start a mock server on port 0 that answers two calls with different
// headers: plenty of tokens left (reset "1s"), then only 900 left (reset "6m0s")
// TODO 4: call it twice with fetch and print one line per call, for example
// requests=59 tokens=48000 -> go on
// requests=58 tokens=900 -> pause 360000 ms
// Pause when fewer than 1000 tokens are left.
// TODO 5: close the serverExpected: Two lines: "requests=59 tokens=48000 -> go on" and "requests=58 tokens=900 -> pause 360000 ms", because 6m0s is six minutes.
Show hint
String.prototype.matchAll with the pattern (\d+(?:\.\d+)?)(ms|h|m|s) walks the pairs, and listing ms before m stops 20ms from being read as 20 minutes.
Show solution
import http from "node:http";
// "1s", "6m0s", "20ms" and "1h2m3.5s" all appear in duration-style header values.
function toMs(text) {
const unit = { ms: 1, s: 1000, m: 60000, h: 3600000 };
let total = 0;
for (const [, amount, name] of text.matchAll(/(\d+(?:\.\d+)?)(ms|h|m|s)/g)) {
total += Number(amount) * unit[name];
}
return total;
}
function readLimits(headers) {
return {
requestsLeft: Number(headers.get("x-ratelimit-remaining-requests")),
tokensLeft: Number(headers.get("x-ratelimit-remaining-tokens")),
tokensResetMs: toMs(headers.get("x-ratelimit-reset-tokens") ?? ""),
};
}
// Mock server: reports a different amount of headroom on every call.
const snapshots = [
{ requests: "59", tokens: "48000", reset: "1s" },
{ requests: "58", tokens: "900", reset: "6m0s" },
];
let calls = 0;
const server = http.createServer((req, res) => {
const snap = snapshots[calls++];
res.writeHead(200, {
"x-ratelimit-remaining-requests": snap.requests,
"x-ratelimit-remaining-tokens": snap.tokens,
"x-ratelimit-reset-tokens": snap.reset,
});
res.end("{}");
});
await new Promise((resolve) => server.listen(0, resolve));
for (let i = 0; i < snapshots.length; i++) {
const res = await fetch("http://127.0.0.1:" + server.address().port);
const { requestsLeft, tokensLeft, tokensResetMs } = readLimits(res.headers);
const pause = tokensLeft < 1000 ? "pause " + tokensResetMs + " ms" : "go on";
console.log("requests=" + requestsLeft, "tokens=" + tokensLeft, "->", pause);
}
server.close();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A call is POST /v1/responses with a Bearer key and a body of model and input; the reply is an id, a status, usage and an output array.
- Read text by filtering message items and their output_text parts, and treat a refusal part as a normal outcome.
- Split 429 in two: slow_down is retried after Retry-After, credit and spend-limit codes stop the loop.
- Keep the key on a server, set spend limits, and validate model output as untrusted data.
OpenAI API — Developer Quickstart — OpenAI