◈AI Codex
Developer PathStep 1 of 21
← Prev·Next →
Infrastructure & DeploymentHow It Works

Your first Claude API call: what you actually need to know

In brief

Auth, the messages array, streaming, structured output, token limits, and the errors you will hit in the first week, updated for the Claude 5.5 models and the October 2026 API version. Everything else you can look up later.

8 min read··API

Contents

♡Sign in to save

This is not a rehash of the docs. The docs are fine. This is the stuff that trips people up in the first week: the mental models that make the API click, the errors you will hit, and the patterns worth getting right from the start.

Updated November 2, 2026 for the Claude 5.5 models and API version 2026-10-21. If you learned the API before October 2026, read what changed in the new API version first.

Prerequisites: You have an Anthropic API key, or you have run ant auth login. You know how to make HTTP requests.

Install the current SDK

pip install --upgrade anthropic          # Python: 2.x
npm install @anthropic-ai/sdk@latest     # TypeScript: 1.x

These are the first SDK versions that send the new API version by default. Two things they change for you:

  • No temperature, top_p or top_k. Sending any of them now returns a 400. Old tutorials set temperature=0.2. Delete it.
  • Your key goes in Authorization: Bearer. The SDK handles this. It only matters if you write raw HTTP.

The request structure

Every request is a POST to https://api.anthropic.com/v1/messages with three required fields: model, max_tokens, and messages.

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY, or your `ant auth login` profile

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=16000,
    messages=[
        {"role": "user", "content": "Explain what a transformer is in two sentences."}
    ],
)

for block in message.content:
    if block.type == "text":
        print(block.text)
import Anthropic from '@anthropic-ai/sdk'

const client = new Anthropic() // reads ANTHROPIC_API_KEY, or your `ant auth login` profile

const message = await client.messages.create({
  model: 'claude-sonnet-5-5',
  max_tokens: 16000,
  messages: [
    { role: 'user', content: 'Explain what a transformer is in two sentences.' },
  ],
})

for (const block of message.content) {
  if (block.type === 'text') console.log(block.text)
}

Why loop over content? Current models think before answering, so the response can contain a thinking block before the text block. content[0].text breaks the day that happens.

Which model

Model ID Price per million tokens (in / out) Use it for
Haiku 5.5 claude-haiku-5-5 $0.10 / $0.50 High-volume, simple tasks
Sonnet 5.5 claude-sonnet-5-5 $2 / $10 Most apps. Start here
Opus 5.5 claude-opus-5-5 $4 / $20 Hard reasoning, agents
Fable 5.2 claude-fable-5-2 $8 / $40 The hardest, longest tasks

All four have a 1M-token context window. Use the exact IDs above, with no date suffix. Our model pricing table stays current.

The messages array

The messages array is the conversation so far. Each entry is a user or assistant turn. The API is stateless: it remembers nothing between requests, so you send the whole history every time.

messages = [
    {"role": "user", "content": "What is the capital of France?"},
    {"role": "assistant", "content": "Paris."},
    {"role": "user", "content": "And the population?"},
]

The first message must be from user. Two rules that changed with the 5.x models:

  • No prefill. You can't end the array with a partial assistant message to steer the reply. It returns a 400. Use structured output or the system prompt instead.
  • Send documents in user messages, never inside an assistant message.

The system prompt

Standing instructions go in the top-level system parameter, not in the messages array.

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=16000,
    system="You are a technical writer. Be precise and concise. Use code examples when relevant.",
    messages=[{"role": "user", "content": "Explain embeddings."}],
)

The system prompt costs input tokens like everything else. If it is long and the same on every request, cache it (below).

Thinking and effort

Current models decide for themselves how much to think. You don't turn thinking on. You choose how hard the model works with effort:

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=16000,
    output_config={"effort": "low"},  # low | medium | high | xhigh | max
    messages=[{"role": "user", "content": "Classify this ticket: ..."}],
)

Use low for chat and classification, medium or high for coding and multi-step work. Older tutorials use budget_tokens. On the 5.x models that returns a 400.

Streaming

For anything user-facing, stream. Waiting for the full response before rendering feels broken, and very long requests can time out without it.

with client.messages.stream(
    model="claude-sonnet-5-5",
    max_tokens=64000,
    messages=[{"role": "user", "content": "Write a haiku about APIs."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    final = stream.get_final_message()
const stream = client.messages.stream({
  model: 'claude-sonnet-5-5',
  max_tokens: 64000,
  messages: [{ role: 'user', content: 'Write a haiku about APIs.' }],
})

stream.on('text', (text) => process.stdout.write(text))
const final = await stream.finalMessage()

Tokens and max_tokens

max_tokens caps the output, not the whole conversation. The context window (1M tokens on current models) covers input plus output.

  • Don't set max_tokens low "to save money". You only pay for what is generated, and a low cap cuts answers off mid-sentence. Around 16,000 for normal requests and 64,000 when streaming is a sensible default.
  • If stop_reason is max_tokens, the answer was cut off. Check it.
  • A rough guide: 1 token is about 4 characters of English, and 1,000 tokens is about 750 words. For exact counts use client.messages.count_tokens(...).

Errors you will hit

Check stop_reason and catch errors by type, not by matching message text.

  • 400 Bad request. Read the message, it is specific. In 2026 the usual causes are a leftover temperature, budget_tokens, a prefilled assistant message, or a model ID with an old date suffix.
  • 401 Unauthorized. Your key is wrong or missing. Never hardcode it.
  • 429 Too many requests. You hit a rate limit. The SDK retries twice by default with backoff; raise it with anthropic.Anthropic(max_retries=4).
  • 500 and 529. Server-side. Retry with backoff; the SDK does this for you.
  • stop_reason: "refusal". Not an error code, a 200. A safety check declined the request. Check stop_reason before you read content.

Structured output

When you need JSON back, don't ask nicely in the prompt. Give a schema, and the response is guaranteed to match it:

import json

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=16000,
    output_config={
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"},
                    "company": {"type": "string"},
                },
                "required": ["name", "email", "company"],
                "additionalProperties": False,
            },
        }
    },
    messages=[{
        "role": "user",
        "content": 'Extract name, email, and company from: "Hi, I\'m Alex Chen from Vercel, alex@vercel.com"',
    }],
)

text = next(b.text for b in message.content if b.type == "text")
data = json.loads(text)

Older code uses a top-level output_format parameter. That is deprecated; use output_config.format.

Cost awareness from day one

Every response tells you what it cost in tokens:

print(message.usage.input_tokens, message.usage.output_tokens)

Output costs five times more than input on every current model. The cheapest wins, in order:

  1. Cache repeated context. Add cache_control={"type": "ephemeral"} to the request and a long, unchanging system prompt or document is billed at 10% on later calls. Check usage.cache_read_input_tokens to confirm it works.
  2. Pick the smallest model that does the job. Haiku 5.5 is 20 times cheaper than Sonnet 5.5.
  3. Use the Batch API for anything that can wait up to a day: 50% off.

What to set up before you build anything larger

  1. Separate API keys per environment: development, staging, production. Revoke them independently.
  2. Log input and output tokens per request. You want this data when usage spikes.
  3. Set a spend limit in the Claude Console so a bug in testing can't run up a bill.
  4. Pin your SDK's major version, so the next API version change happens when you choose.

The rest, such as tools, agents and routing between models, you can add when you have a reason to. Get the basics right first.


Next: Streaming responses properly · What changed in API version 2026-10-21 · Cutting your Claude bill

Official training on this: Claude Platform 101 (13 lessons · 1.5 hr) · Building with the Claude API (67 lessons · 9 hr) on Claude Academy, free.

Related tools

Next in Developer Path · Step 2 of 21

Continue to the next article in the learning path

Next article →

Weekly brief

For people actually using Claude at work.

Each week: one thing Claude can do in your work that most people haven't figured out yet — plus the failure modes to avoid. No tutorials. No hype.

No spam. Unsubscribe anytime.

What to read next

Picked for where you are now

All articles →