#The Messages API: request and response
AddedEverything you do with Claude from code goes through one endpoint: POST /v1/messages. You send a model ID, a ceiling on how many tokens the reply may use, and a list of messages; you get back one assistant message. Tools, structured output, images, PDFs and thinking are all extra fields on that same request, not separate APIs. Once you can read one request and one response fluently, the rest of this course is variations.
The mental model: a function call to a very expensive, stateless pure function. You pass in the whole situation every time (model, system, messages, tools), and you get back a value (content) plus a receipt (usage) and a reason it stopped (stop_reason). Nothing is remembered on the server between calls unless you use a feature that says it does. That is why the request looks the way it does, and why most production bugs are about what you did or didn't put in it.
The request has three required fields:
| Field | What it is | Notes |
|---|---|---|
model | The exact model ID, e.g. claude-opus-5-5 | Use the IDs exactly as published; current models have no date suffix |
max_tokens | The most output tokens this reply may use | A hard cap the model doesn't see; hitting it cuts the reply off |
messages | The conversation so far: { role, content } objects | Must start with a user message; content is a string or a list of content blocks |
The response is a message object: id (msg_…), role: "assistant", model, a content array of content blocks (each with a type: text, thinking, tool_use and others), stop_reason, stop_details (filled only for refusals), and usage, the token counts you are billed for. The current models as of December 2026, from Anthropic's model and pricing pages:
| Model | ID | Input / output per million tokens | Context / max output |
|---|---|---|---|
| Claude Opus 5.5 | claude-opus-5-5 | $4 / $20 | 1M / 128K |
| Claude Sonnet 5.5 | claude-sonnet-5-5 | $2 / $10 | 1M / 128K |
| Claude Haiku 5.5 | claude-haiku-5-5 | $0.10 / $0.50 (prompts up to 100K tokens) | 1M / 128K |
| Claude Fable 5.2 | claude-fable-5-2 | $8 / $40 | 1M / 128K |
Parameters that no longer exist on current models. If you learnt the API from older tutorials, these surprise people, and they all return 400 invalid_request_error on the current models:
temperature,top_pandtop_k: rejected on every model from API version2026-10-21(the version SDK 1.17.0 sends). You steer variety with the prompt and depth with effort instead (Sampling explains what they did).thinking: { type: "enabled", budget_tokens: N }: rejected on Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.2; adaptive thinking plusoutput_config.effortreplaced it (Thinking and effort in requests).- Assistant prefill (ending
messageswith a partialassistantturn to force how the reply starts): rejected. Use structured outputs (output_config.format) or instructions.
import Anthropic from "@anthropic-ai/sdk";
// Scripted replies (see "How these examples run")
async function fetch(url, init) {
const headers = new Headers(init.headers);
console.log(`> ${init.method} ${new URL(url).pathname}`);
console.log(`> anthropic-version: ${headers.get("anthropic-version")}, authorization: ${headers.get("authorization")}`);
console.log(`> body: ${init.body}`);
return Response.json(
{
id: "msg_01HcLx4s9VnR2qEe7TfJdWp3",
type: "message",
role: "assistant",
model: "claude-opus-5-5",
content: [{ type: "text", text: "A token is a chunk of text, often a word or part of a word, that the model reads and writes one at a time.", citations: null }],
stop_reason: "end_turn",
stop_sequence: null,
stop_details: null,
container: null,
diagnostics: null,
usage: {
input_tokens: 19, output_tokens: 31,
cache_creation_input_tokens: 0, cache_read_input_tokens: 0,
cache_creation: { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: 0 },
output_tokens_details: { thinking_tokens: 0 },
server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard",
},
},
{ headers: { "request-id": "req_011CYf3k8vQe2LpR9sTdWx4N" } },
);
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: "In one sentence, what is a token?" }],
});
for (const block of response.content) {
if (block.type === "text") console.log("text:", block.text);
}
console.log("stop_reason:", response.stop_reason);
console.log("usage:", response.usage.input_tokens, "input tokens,", response.usage.output_tokens, "output tokens");
console.log("message id:", response.id, "| request id:", response._request_id);> POST /v1/messages
> anthropic-version: 2026-10-21, authorization: Bearer sk-ant-test
> body: {"model":"claude-opus-5-5","max_tokens":1024,"messages":[{"role":"user","content":"In one sentence, what is a token?"}]}
text: A token is a chunk of text, often a word or part of a word, that the model reads and writes one at a time.
stop_reason: end_turn
usage: 19 input tokens, 31 output tokens
message id: msg_01HcLx4s9VnR2qEe7TfJdWp3 | request id: req_011CYf3k8vQe2LpR9sTdWx4Nnew Anthropic({ apiKey, fetch })builds the client. In production you'd writenew Anthropic()and the SDK would findANTHROPIC_API_KEY(or anant auth loginprofile); here the scriptedfetchstands in for the network so you can see exactly what goes over the wire.client.messages.create({...})serialises the three required fields into JSON and sendsPOST /v1/messages. The>lines show it: the SDK adds theanthropic-version: 2026-10-21header itself (it's hard-coded in SDK 1.17.0) and sends the key asAuthorization: Bearer …(older SDKs and many tutorials use anx-api-keyheader; the API accepts either, and Anthropic's current curl examples use the bearer form). The version header pins the API's behaviour, which is why upgrading the SDK can change what the API accepts.- The reply's
contentis an array, not a string. Even a plain answer is onetextblock, and on current models the same array can also holdthinkingortool_useblocks, so the loop checksblock.typebefore reading.text. In TypeScript,response.content[0].textdoesn't even compile, becausecontent[0]could be a block withouttext. stop_reason: "end_turn"means the model finished on its own. Always look at it:max_tokensmeans the answer was cut off,refusalmeans there is no answer (Stop reasons and refusals).usageis the bill: 19 input tokens (your prompt plus the API's own formatting) and 31 output tokens. Output is what you pay most for, at five times the input price on Opus 5.5.response._request_idcomes from therequest-idresponse header. Log it with every call: it's the first thing Anthropic support asks for, and it's how you join your logs to theirs.
max_tokens is a ceiling, not a targetmax_tokens is a ceiling, not a target. The model doesn't see it and doesn't aim for it; it just gets cut off if it reaches it. Set it to the most you'd ever accept for that feature (a classifier: a few hundred; a chat answer: a few thousand; long generation: stream it and allow tens of thousands). Two practical limits apply. The model's own maximum is 128K output tokens on the current models. And the TypeScript SDK refuses a non-streaming request whose max_tokens implies it could run longer than ten minutes (the check in SDK 1.17.0 is 60 min × max_tokens / 128000 > 10 min, so anything above 21,333), throwing Streaming is required for operations that may take longer than 10 minutes before sending anything. For big outputs you stream (Streaming responses).
content[0].text is a bug waiting to happenA request to claude-opus-5-5 reports usage: { input_tokens: 1200, output_tokens: 800 } with no caching. Using the price table above, what did it cost, and which part dominates?
Show answer
$0.0208, and output is 77% of it even though it's fewer tokens.
- Input: 1,200 tokens × $4 per million = 1,200 × 0.000004 = $0.0048.
- Output: 800 tokens × $20 per million = 800 × 0.00002 = $0.016.
- Total: 0.0048 + 0.016 = $0.0208. At a million such requests a month that's $20,800.
- Output is 0.016 / 0.0208 ≈ 77% of the cost. Output tokens are generated one at a time, which is why every provider prices them several times higher than input (Next-token prediction explains the generation loop).
- So the cheapest lever is usually shorter answers (ask for them, cap
max_tokens, use structured output), not a shorter prompt.