← Blog

Anthropic Claude API Documentation Examples Guide

2026-09-25 · 4 min read · SubToAPI Team

Most developers searching for Anthropic Claude API documentation examples aren't looking for a link to the official docs — they've probably already been there. What they want is working code: real request payloads, real response shapes, and enough context to know why a call succeeded or failed. This article collects the examples you actually need to get a Claude integration running, organized by the tasks developers hit most often.

We'll cover authentication, basic messages, system prompts, multi-turn conversations, streaming, tool use, and error handling — with copy-pasteable curl and JavaScript snippets. Where relevant, we'll also show the equivalent request through SubToAPI, which wraps Claude access behind a standard HTTPS API with its own key format, so the same patterns apply whether you're calling Anthropic directly or through a proxy layer.

Basic Message Request

The core of the Claude API is the Messages endpoint. Here's a minimal example:

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "Explain what a mutex is in one paragraph."}
    ]
  }'

Every request needs a model, a max_tokens cap, and a messages array. The response includes a content array (not a single string), usage metadata, and a stop_reason:

{
  "id": "msg_01XyZ...",
  "type": "message",
  "role": "assistant",
  "content": [
    {"type": "text", "text": "A mutex (mutual exclusion) is a synchronization primitive..."}
  ],
  "model": "claude-sonnet-4-20250514",
  "stop_reason": "end_turn",
  "usage": {"input_tokens": 14, "output_tokens": 58}
}

Parsing content[0].text instead of a top-level text field trips up a lot of people migrating from other APIs — Claude's content array supports multiple blocks (text, tool use, images), so it's structured that way from the start.

Adding a System Prompt

System prompts are a separate top-level field, not a message with role: "system":

{
  "model": "claude-sonnet-4-20250514",
  "max_tokens": 1024,
  "system": "You are a terse API documentation assistant. Answer in code where possible.",
  "messages": [
    {"role": "user", "content": "How do I paginate a GET request?"}
  ]
}

Multi-Turn Conversations

Claude's API is stateless — you resend the full conversation history on every call:

{
  "model": "claude-sonnet-4-20250514",
  "max_tokens": 1024,
  "messages": [
    {"role": "user", "content": "What's the capital of Peru?"},
    {"role": "assistant", "content": "Lima."},
    {"role": "user", "content": "What's its population?"}
  ]
}

Messages must alternate user and assistant. Sending two user messages in a row without an assistant reply in between returns a validation error.

Streaming Responses

Set "stream": true and the API returns server-sent events instead of a single JSON blob:

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "stream": true,
    "messages": [{"role": "user", "content": "Write a haiku about servers."}]
  }'

You'll receive a sequence of events (message_start, content_block_delta, message_delta, message_stop). Each content_block_delta event carries a small chunk of text — concatenate them client-side to reconstruct the full response as it arrives.

Tool Use Example

Tool use lets Claude request a function call instead of (or alongside) a text answer:

{
  "model": "claude-sonnet-4-20250514",
  "max_tokens": 1024,
  "tools": [
    {
      "name": "get_weather",
      "description": "Get current weather for a city",
      "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"]
      }
    }
  ],
  "messages": [
    {"role": "user", "content": "What's the weather in Lisbon?"}
  ]
}

When Claude decides to use a tool, stop_reason will be tool_use and the content array will include a block with type: "tool_use", the tool name, and structured input. You then run the function yourself and send the result back as a tool_result block in the next message.

Calling Claude Through SubToAPI

If you're already using Claude through a subscription rather than a raw Anthropic API key, SubToAPI exposes the same Messages-style interface using application keys (sub_live_...) instead of account-level credentials:

const res = await fetch("https://api.subtoapi.app/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    model: "claude-sonnet-4-20250514",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Summarize this changelog." }]
  })
});
const data = await res.json();

The request and response shapes mirror what's shown above, which makes it easy to switch between a direct Anthropic integration and a SubToAPI-issued key without rewriting your parsing logic. Full request/response examples for messages, streaming, and tools live in the docs, with a fast setup path in the quickstart.

Handling Errors

Every non-2xx response returns a JSON body with an error object:

{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "max_tokens: Field required"
  }
}

Common error types to handle explicitly: invalid_request_error (malformed payload), authentication_error (bad key), rate_limit_error (back off and retry), and overloaded_error (retry with backoff — this isn't your fault). Always check error.type rather than just the HTTP status code, since a 400 can mean several different validation failures.

questions

Where can I find official example requests for the Claude Messages API? Anthropic's own documentation has a reference for every field, but the examples above cover the request/response shapes you'll use in 90% of real integrations: basic messages, system prompts, streaming, and tool use.

Why does my multi-turn request fail with a role error? Claude requires strict alternation between user and assistant messages. Check that you're appending the assistant's reply to your history before sending the next user message — a common bug is sending two consecutive user messages.

Can I use these same request examples with SubToAPI instead of a raw Anthropic key? Yes. SubToAPI's Messages endpoint accepts the same JSON structure — just swap the base URL and use a sub_live_ key in the Authorization header instead of x-api-key.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →