Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

Claude (Anthropic) API

API TutorialLesson 1935 min

What you'll walk away with

  • Build a POST /v1/messages request with the required headers and the three required body fields
  • Read the reply by filtering content blocks of type text instead of indexing content[0]
  • Use stop_reason and usage to detect a cut-off answer and to count tokens
  • Handle 401, 429 with retry-after, and 5xx errors from the typed error body, with the key kept on a server

Explain it simply

Explain it simply

Claude is a language model that lives on Anthropic's servers. To talk to it from your own program you send one HTTP request, and one HTTP response comes back with the answer inside it. For a normal call there is no chat window, no session and no socket you have to keep open.

Think of a post-office counter. You hand over an envelope with your membership card on the front (the API key), a note saying which edition of the form you used (the version header) and a letter inside (the list of messages). The clerk reads it, writes a reply and hands back a second envelope. If the card is wrong, the form is incomplete or the counter is busy, you get a short slip that says exactly what went wrong instead of a letter.

Problem → Why → Solution

The problem: a snippet that fails four ways

Below is the snippet many people write first after reading a blog post. It runs in a web page, the key sits in the source, the model name was copied from an old article, and the answer is read from the first content item.

Several things go wrong at once. Every visitor can open the developer tools and copy the key. A browser request to this API is cross-origin, so it only works at all when a special opt-in header is added. The request has no anthropic-version header and no max_tokens, so the server answers 400. And even after those are fixed, the first content block is not guaranteed to be text, so content[0].text can be undefined.

page.js
// runs in the browser: every visitor can read the key below
const res = await fetch("https://api.anthropic.com/v1/messages", {
  method: "POST",
  headers: { "x-api-key": "sk-ant-api03-MY-REAL-KEY" },
  body: JSON.stringify({
    model: "claude-some-old-model",
    messages: [{ role: "user", content: "Hello" }],
  }),
});
console.log((await res.json()).content[0].text);

Why one small snippet breaks so often

The Messages API is a contract: three headers, three body fields, a typed error when you break the contract and a list of content blocks instead of one string. Each failure above is a rule of that contract being ignored. Fixing them means moving the call to a server you control, sending the whole contract and reading the reply by block type.

Core concept: five parts of a Messages call

A Messages API call is a small, strict contract. Learn its five parts once and every request you write afterwards will look familiar.

1. Endpoint and three headers

Send POST to https://api.anthropic.com/v1/messages. The x-api-key header carries your secret; the current authentication guide also accepts Authorization: Bearer with the same key. anthropic-version names the API revision and is required (the current docs show 2026-10-21, and the official SDKs set it for you). content-type must be application/json.

2. Body: model, max_tokens, messages

model picks the model by its exact id from Anthropic's model list. max_tokens is a hard ceiling on how much the model may write. messages is an array of objects, each with a role of user or assistant and a content string. A system prompt is not a message; it has its own top-level system field.

3. The API remembers nothing

Every call stands alone. To continue a conversation you append Claude's last reply as an assistant message, add the new user message and send the whole list again. Longer lists mean more input tokens.

4. The reply is a list of content blocks

A success returns id, type message, role assistant, a content array, the model, stop_reason and usage. Every block has a type. Text lives in blocks of type text; depending on the model and settings the array can also hold thinking or tool_use blocks, so filter by type instead of reading content[0].

5. stop_reason and usage

stop_reason explains why generation ended: end_turn for a natural finish, max_tokens when your ceiling cut the answer off, and other values for tool use or refusals. usage counts input_tokens and output_tokens, which is what you are billed on and what rate limits measure.

Statuserror.typeWhat to do
400invalid_request_errorFix the body or a header
401authentication_errorCheck or rotate the key
404not_found_errorCheck the path and model id
429rate_limit_errorWait for retry-after, retry
500 / 529api_error / overloaded_errorRetry with backoff

Never call this API from browser code

Anyone who loads the page can read the key. Browsers also add an Origin header, and the API refuses such direct requests unless a special anthropic-dangerous-direct-browser-access header is sent, which the docs reserve for cases where exposing a key is acceptable. Organizations with zero data retention cannot make browser requests at all. Keep the key on your own back end and let your front end call that.

Mental model: a form with a typed reply slip
  1. Headers carry key and API version
  2. Body: model, max_tokens, messages
  3. Reply is a list of typed blocks
  4. stop_reason and usage close the loop

Treat every field as required until the docs say it is optional, and treat every reply as a list you filter, never a string you index.

General pattern

bash
curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: <api-version>" \
  -H "content-type: application/json" \
  -d '{
    "model": "<model-id>",
    "max_tokens": <output-limit>,
    "messages": [{"role": "user", "content": "<prompt>"}]
  }'

Replace each angle-bracket placeholder with a value from the current docs. This shows the shape only; run a real call with your own key stored in an environment variable, never pasted into the command line or a file you commit.

Calling a mock Messages API from Node

No real key or network is needed. The script starts a small server on a free port that answers in the same shape as the real endpoint, then uses fetch to build the request, check res.ok, read the content blocks and handle a typed error. The mock reply deliberately starts with an empty thinking block, the way current models may reply, so you can see why content[0].text fails and a type filter works.

claude-client.mjs
import http from "node:http";

const KEY = "sk-ant-demo-key";
const MODEL = "claude-opus-5-5";

// Mock server: same SHAPE as POST /v1/messages, no network and no real key.
let burstCalls = 0;
const server = http.createServer((req, res) => {
  let raw = "";
  req.on("data", (chunk) => (raw += chunk));
  req.on("end", () => {
    const reply = (status, body, headers = {}) => {
      res.writeHead(status, { "content-type": "application/json", ...headers });
      res.end(JSON.stringify(body));
    };
    const fail = (status, type, message, headers) =>
      reply(
        status,
        { type: "error", error: { type, message }, request_id: "req_demo" },
        headers,
      );

    if (req.headers["x-api-key"] !== KEY) {
      return fail(401, "authentication_error", "invalid x-api-key");
    }
    if (!req.headers["anthropic-version"]) {
      return fail(400, "invalid_request_error", "anthropic-version header is required");
    }
    const body = JSON.parse(raw);
    if (!body.model || !body.max_tokens || !Array.isArray(body.messages)) {
      return fail(400, "invalid_request_error", "model, max_tokens, messages required");
    }
    const prompt = body.messages.at(-1).content;
    if (prompt === "burst" && burstCalls++ === 0) {
      return fail(429, "rate_limit_error", "rate limit exceeded", { "retry-after": "0" });
    }
    reply(200, {
      id: "msg_demo",
      type: "message",
      role: "assistant",
      content: [
        { type: "thinking", thinking: "", signature: "demo-signature" },
        { type: "text", text: "Mingalaba! I am a mock Claude." },
      ],
      model: body.model,
      stop_reason: "end_turn",
      stop_sequence: null,
      usage: { input_tokens: 14, output_tokens: 11 },
    });
  });
});

// The client code: build the request, check res.ok, read the typed error body.
async function askClaude(baseUrl, apiKey, body) {
  const res = await fetch(baseUrl + "/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": apiKey,
      "anthropic-version": "2026-10-21",
      "content-type": "application/json",
    },
    body: JSON.stringify(body),
  });
  const data = await res.json();
  if (!res.ok) {
    const err = new Error(data.error.type + ": " + data.error.message);
    err.status = res.status;
    const wait = res.headers.get("retry-after");
    err.retryAfter = wait === null ? undefined : Number(wait);
    throw err;
  }
  return data;
}

const textOf = (message) =>
  message.content
    .filter((block) => block.type === "text")
    .map((block) => block.text)
    .join("");

async function withRetry(call, attempts = 3) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await call();
    } catch (err) {
      const retryable = err.status === 429 || err.status >= 500;
      if (!retryable || attempt === attempts) throw err;
      const waitMs =
        err.retryAfter === undefined ? 2 ** attempt * 100 : err.retryAfter * 1000;
      await new Promise((resolve) => setTimeout(resolve, waitMs));
      console.log("retry " + attempt + " after " + err.status);
    }
  }
}

await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;
const ask = (prompt) => ({
  model: MODEL,
  max_tokens: 256,
  messages: [{ role: "user", content: prompt }],
});

const message = await askClaude(base, KEY, ask("Say hello"));
console.log("block types:", message.content.map((block) => block.type).join(", "));
console.log("content[0].text:", message.content[0].text);
console.log("text blocks:", textOf(message));
console.log("stop_reason:", message.stop_reason);
const { input_tokens, output_tokens } = message.usage;
console.log("usage:", input_tokens, "in /", output_tokens, "out");

const bad = [
  ["wrong key", "sk-ant-oops", ask("hi")],
  ["no max_tokens", KEY, { model: MODEL, messages: ask("hi").messages }],
];
for (const [label, key, body] of bad) {
  try {
    await askClaude(base, key, body);
  } catch (err) {
    console.log(label + " ->", err.status, err.message);
  }
}

const again = await withRetry(() => askClaude(base, KEY, ask("burst")));
console.log("after retry:", again.stop_reason);
server.close();

Code breakdown

  1. Version header"anthropic-version": "2026-10-21",

    Next to x-api-key and content-type, this header pins the API revision. The mock rejects a request without it, just as the real API does.

  2. Typed error bodyconst err = new Error(data.error.type + ": " + data.error.message);

    Failures arrive as JSON with a type and a message, so the code builds one readable Error and keeps the HTTP status on it for the retry logic.

  3. Filter by block type.filter((block) => block.type === "text")

    Only text blocks are joined. The printed block types are thinking, text, so content[0].text is undefined while textOf() returns the greeting.

  4. Retry only what can recoverconst retryable = err.status === 429 || err.status >= 500;

    A 400 or 401 will fail the same way tomorrow, so only rate limits and server errors are retried, and only up to a fixed number of attempts.

  5. Honour retry-aftererr.retryAfter === undefined ? 2 ** attempt * 100 : err.retryAfter * 1000;

    When the server says how long to wait the code obeys; when it says nothing the wait doubles on each attempt (200 ms, then 400 ms).

  6. Usage numbersconsole.log("usage:", input_tokens, "in /", output_tokens, "out");

    usage reports the tokens this call consumed, the numbers that drive your bill and your rate limits. Log them for every request.

You should see
block types: thinking, text
content[0].text: undefined
text blocks: Mingalaba! I am a mock Claude.
stop_reason: end_turn
usage: 14 in / 11 out
wrong key -> 401 authentication_error: invalid x-api-key
no max_tokens -> 400 invalid_request_error: model, max_tokens, messages required
retry 1 after 429
after retry: end_turn

The same call with curl

curl is the quickest way to check a key and a model id before you write any code. The command below prints only the text blocks, using jq to filter by type exactly as the Node client does. It is illustrative: check the current docs and run it with your own key in ANTHROPIC_API_KEY.

bash
# Illustrative - check the current docs, and use your own key in ANTHROPIC_API_KEY.
curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 256,
    "messages": [{"role": "user", "content": "Say hello in Burmese."}]
  }' | jq -r '.content[] | select(.type == "text") | .text'

Add -i to see response headers. Every response carries a request-id header, and the same value appears as request_id in an error body; quote it when you contact support.

Streaming: tokens as they are generated

A long answer can take many seconds. With "stream": true in the body the API answers with server-sent events, so your UI can show words while the model is still writing. The documented flow is message_start, then for each content block a content_block_start, any number of content_block_delta events and a content_block_stop, then message_delta carrying stop_reason, and finally message_stop. ping events can appear anywhere.

stream-reader.mjs
import http from "node:http";

// Mock server: the documented event flow of a streamed message.
const msg = { id: "msg_demo", type: "message", role: "assistant", content: [] };
const delta = (text) => ({
  type: "content_block_delta",
  index: 0,
  delta: { type: "text_delta", text },
});
const events = [
  ["message_start", { type: "message_start", message: { ...msg, stop_reason: null } }],
  ["content_block_start", { type: "content_block_start", index: 0,
    content_block: { type: "text", text: "" } }],
  ["ping", { type: "ping" }],
  ["content_block_delta", delta("Ming")],
  ["content_block_delta", delta("alaba!")],
  ["content_block_stop", { type: "content_block_stop", index: 0 }],
  ["message_delta", { type: "message_delta", delta: { stop_reason: "end_turn" },
    usage: { output_tokens: 9 } }],
  ["message_stop", { type: "message_stop" }],
];
const server = http.createServer((req, res) => {
  res.writeHead(200, { "content-type": "text/event-stream" });
  for (const [name, data] of events) {
    res.write("event: " + name + "\ndata: " + JSON.stringify(data) + "\n\n");
  }
  res.end();
});
await new Promise((resolve) => server.listen(0, resolve));

// Client: split the byte stream into frames, then react to each event type.
const res = await fetch("http://127.0.0.1:" + server.address().port + "/v1/messages", {
  method: "POST",
  body: JSON.stringify({ stream: true }),
});
const decoder = new TextDecoder();
let buffer = "";
let text = "";
let stopReason = null;
let outputTokens = 0;
for await (const chunk of res.body) {
  buffer += decoder.decode(chunk, { stream: true });
  let end;
  while ((end = buffer.indexOf("\n\n")) !== -1) {
    const frame = buffer.slice(0, end);
    buffer = buffer.slice(end + 2);
    const line = frame.split("\n").find((l) => l.startsWith("data: "));
    if (!line) continue;
    const event = JSON.parse(line.slice(6));
    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
      text += event.delta.text;
      console.log("delta:", JSON.stringify(event.delta.text));
    } else if (event.type === "message_delta") {
      stopReason = event.delta.stop_reason;
      outputTokens = event.usage.output_tokens;
    } else if (event.type === "error") {
      throw new Error(event.error.type);
    }
  }
}
console.log("text:", text);
console.log("stop_reason:", stopReason, "| output tokens so far:", outputTokens);
server.close();

Errors can arrive after a 200

Once the stream has started the HTTP status is already 200, so a later failure comes as an event named error, for example an overloaded_error. Handle that event, and ignore event types you do not recognise, because new ones can be added. The token counts in message_delta are cumulative, not per event.

Limits, cost and refusals

Rate limits on the Messages API are measured in requests per minute, input tokens per minute and output tokens per minute, separately for each model class and usage tier. A 429 response usually carries retry-after, and anthropic-ratelimit-* headers report how much headroom is left. Billing is per token, so a sensible max_tokens is also a cost control. Look up prices on the official pricing page instead of copying numbers into code.

  • A 429 from a monthly spend cap has no retry-after and keeps failing until access resumes, so every retry loop needs an attempt limit.
  • Some newer models can decline a request: you still get HTTP 200, but stop_reason is refusal, so check stop_reason before using the content.
  • Log the request-id header and the usage numbers, never the key or the full prompt.

In real projects

How to apply it in a real project

In a real product the call lives in one server-side module, never in the front end. The browser asks your endpoint, your endpoint checks who the user is and what they may spend, and only then calls Claude. That module reads the model id and max_tokens from configuration, sets a timeout, logs the request-id and token usage, and retries only 429 and 5xx responses.

Treat the reply as untrusted text: escape it before putting it in HTML and validate it before parsing it as JSON. Test the module against a mock server that returns a success, a 401, a 429 with retry-after, a 529 and a malformed body, so those paths are exercised long before a real outage exercises them for you.

Common mistakes

Common mistakes

Most Claude integration bugs are small contract slips. These three cost people the most time.

Reading content[0].text

It works in the first test and breaks later, when the reply begins with a thinking block or ends with a tool_use block. Always filter content by type and join the text blocks.

Leaving out max_tokens or the version header

Both are required, and the API answers 400 invalid_request_error without them. Read the message in the error body; it names the missing piece. Retrying the same request will never fix it.

Retrying every failure

A 400 or 401 is a bug in your request or key, not bad luck. Only 429 and 5xx deserve a retry, with a delay and an attempt limit. An unlimited loop turns one outage into a pile of billed, failing requests.

Best practices

Habits worth keeping

  • Take the model id from configuration and from the official model list; if a call returns 404 not_found_error, suspect the id first.
  • Prefer the official SDK in application code, because it sets headers, retries and parses streams for you; keep raw HTTP for learning, debugging and unsupported languages.
  • Cap output with max_tokens per feature, and keep a per-user budget in your own back end.

Mini challenge

Build a truncation and cost guard

Write summarize(message) for Messages API replies. It must return the joined text of every text block, whether the answer was cut off by max_tokens, and the cost in dollars computed from the usage object with prices you define. Prove it with a mock server that answers one complete message and one truncated message.

  • Join only blocks whose type is text
  • Report truncated when stop_reason is max_tokens
  • Compute the cost from input_tokens and output_tokens with example prices per million tokens
  • Run against a mock server on port 0 and close it at the end
guard.mjs
import http from "node:http";

// Example prices in USD per million tokens - not real prices.
const PRICE = { input: 3, output: 15 };

function summarize(message) {
  // TODO 1: join the text of every content block whose type is "text"
  // TODO 2: truncated is true when stop_reason is "max_tokens"
  // TODO 3: costUsd = tokens * price / 1,000,000, rounded to 6 decimals
  return { text: "", truncated: false, costUsd: 0 };
}

// TODO 4: start a mock server on port 0. For max_tokens 256 it answers with a
//   finished message (stop_reason "end_turn"); for max_tokens 5 with a message
//   whose stop_reason is "max_tokens". Include a usage object in both.

// TODO 5: POST both max_tokens values with fetch, run summarize() on each reply
//   and print one line per call, for example:
//   max_tokens=256 | Mingalaba! | truncated=false | $0.000171

// TODO 6: close the server when you are done

Expected: Two lines: the full message with truncated=false and a cost of $0.000171, then the cut-off message with truncated=true and $0.000135.

Show hint

cost = (input_tokens * inputPrice + output_tokens * outputPrice) / 1,000,000. Use toFixed(6) and Number() so 0.000171 prints cleanly.

Show solution
guard.mjs
import http from "node:http";

// Example prices in USD per million tokens - not real prices.
const PRICE = { input: 3, output: 15 };

function summarize(message) {
  const texts = message.content.filter((b) => b.type === "text");
  const { input_tokens, output_tokens } = message.usage;
  const dollars = (input_tokens * PRICE.input + output_tokens * PRICE.output) / 1e6;
  return {
    text: texts.map((b) => b.text).join(""),
    truncated: message.stop_reason === "max_tokens",
    costUsd: Number(dollars.toFixed(6)),
  };
}

const replies = {
  complete: {
    content: [{ type: "text", text: "Mingalaba!" }],
    stop_reason: "end_turn",
    usage: { input_tokens: 12, output_tokens: 9 },
  },
  cutOff: {
    content: [{ type: "text", text: "Myanmar is a country in" }],
    stop_reason: "max_tokens",
    usage: { input_tokens: 20, output_tokens: 5 },
  },
};
const server = http.createServer((req, res) => {
  let raw = "";
  req.on("data", (chunk) => (raw += chunk));
  req.on("end", () => {
    const { max_tokens } = JSON.parse(raw);
    res.writeHead(200, { "content-type": "application/json" });
    res.end(JSON.stringify(max_tokens < 10 ? replies.cutOff : replies.complete));
  });
});
await new Promise((resolve) => server.listen(0, resolve));

for (const maxTokens of [256, 5]) {
  const res = await fetch("http://127.0.0.1:" + server.address().port, {
    method: "POST",
    body: JSON.stringify({ max_tokens: maxTokens }),
  });
  const { text, truncated, costUsd } = summarize(await res.json());
  const flag = "truncated=" + truncated;
  console.log("max_tokens=" + maxTokens, "|", text, "|", flag, "| $" + costUsd);
}
server.close();

Quick quiz 1 / 3

A reply arrives with content: [{ type: "thinking", thinking: "" }, { type: "text", text: "Hi" }]. Which approach reads the answer safely?

Quick quiz 2 / 3

stop_reason comes back as max_tokens and the text stops mid-sentence. What happened?

Quick quiz 3 / 3

A request fails with 429 rate_limit_error and a retry-after: 20 header. What is the right next step?

What to remember

  • A call is POST /v1/messages with x-api-key, anthropic-version and content-type headers and a body of model, max_tokens and messages.
  • Read replies by filtering content blocks of type text, and check stop_reason and usage every time.
  • Errors are JSON with a type and message: fix 400 and 401, wait for retry-after on 429, back off on 5xx.
  • Keep the key and the model id on your server; never ship them in browser code.

Claude API — Messages — Anthropic

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Claude (Anthropic) API | Thuta Learning