Claude API — Complete Developer’s Guide

The Claude API gives you programmatic access to Anthropic’s Claude models through a single HTTPS endpoint: POST https://api.anthropic.com/v1/messages. You send a list of messages, you get a model-generated response back, and everything else — tool use, structured outputs, extended reasoning, caching — is a feature of that one endpoint. This guide covers everything I wish I’d had on day one: how the API is organized, what a request actually looks like, which model to pick, and the 2026 features that separate a demo from a production integration.

TL;DR: The Claude API is a single Messages endpoint plus supporting APIs (Batches, Files, Token Counting, Models). You authenticate with an x-api-key header from a key created at platform.claude.com. Current models are Claude Opus 4.8 ($5/$25 per MTok), Claude Sonnet 5 ($3/$15, intro $2/$10 through Aug 31, 2026), and Claude Haiku 4.5 ($1/$5). The 2026 feature set — adaptive thinking, the effort parameter, structured outputs, prompt caching, and the Batch API — can cut costs by 50–90% when used well. Note: temperature is removed on current models.

What the Claude API is (and is not)

The Claude API — formally the Anthropic API — is the developer interface to the same models that power the claude.ai chat apps. It is billed separately from consumer subscriptions: a Claude Pro plan does not include API credits, and API usage does not touch your chat limits. If you’re deciding between the two, the rule of thumb is simple: humans chat on claude.ai, software calls the API.

Architecturally, almost everything routes through the Messages endpoint. A handful of supporting endpoints exist for specific jobs: /v1/messages/batches for asynchronous bulk work, /v1/files for reusable file uploads, /v1/messages/count_tokens for pre-flight token counting, and /v1/models for live model discovery. There is no separate “chat API” versus “completion API” — one request shape covers text generation, vision input, tool calling, and JSON extraction.

Getting access: Console, API keys, and SDKs

Everything starts at the Claude Console. You create an account, add billing, and generate an API key scoped to a workspace. The key is shown once — store it in an environment variable, never in source code. I’ve written a full step-by-step walkthrough in the Claude AI API key guide, including workspace strategy and what to do when you hit a 401.

Anthropic ships official SDKs for Python (pip install anthropic), TypeScript (npm install @anthropic-ai/sdk), Java, Go, Ruby, C#, and PHP. The SDKs read ANTHROPIC_API_KEY from the environment automatically, retry rate-limited and 5xx requests with exponential backoff, and expose typed exception classes. Use them — hand-rolled HTTP clients tend to reimplement retry logic badly. JavaScript developers can follow the whole flow, from install to streaming, in the Claude API Node.js guide.

Anatomy of a Claude API request

Three headers are required on every raw HTTP call: x-api-key, anthropic-version: 2023-06-01, and content-type: application/json. The body needs a model, a max_tokens cap, and a messages array. Here is the smallest complete request:

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-5",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "Explain prompt caching in one paragraph."}
    ]
  }'

The same call in Python, which is what most of my production code looks like:

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain prompt caching in one paragraph."}
    ],
)
print(message.content[0].text)

The response is a message object with a content array (text blocks, tool-use blocks, or thinking blocks), a stop_reason (end_turn, max_tokens, tool_use, or refusal), and a usage object with exact input and output token counts. That usage object is your billing source of truth — log it from day one.

Two request-shape rules trip up developers migrating old code: messages must alternate between user and assistant roles starting with user, and the sampling parameters temperature, top_p, and top_k are removed on Opus 4.7+, Sonnet 5, and newer models — sending them returns a 400. Steer output style with prompting instead.

Which Claude model should you call?

As of July 2026 there are three tiers you’ll realistically choose between, plus previous-generation models that remain active. All current Opus and Sonnet models have a 1 million token context window; Haiku 4.5 keeps the classic 200K window.

ModelAPI IDInput / Output per MTokContextBest for
Claude Opus 4.8claude-opus-4-8$5 / $251MDemanding reasoning, long agentic runs, code review
Claude Sonnet 5claude-sonnet-5$3 / $15 (intro $2 / $10 to Aug 31, 2026)1MProduction default; near-Opus coding quality
Claude Haiku 4.5claude-haiku-4-5$1 / $5200KClassification, routing, high-volume simple tasks

My working heuristic from daily API work across the lineup (and with the current trio since their launches): start on Sonnet 5, drop to Haiku 4.5 where an eval proves it holds up, and reserve Opus 4.8 for the requests where correctness is worth 2–3× the cost. Anthropic’s flagship Claude Fable 5 ($10/$50) sits above Opus for the hardest long-horizon work, but it’s rarely the right starting point for a new integration. For a deeper comparison of the tiers, see the Claude models explained guide.

The 2026 Claude API feature set

Adaptive thinking and the effort parameter

Extended thinking used to require a fixed budget_tokens number you had to tune by hand. On current models that’s gone — you enable adaptive thinking and Claude decides when and how deeply to reason. The old {"type": "enabled", "budget_tokens": N} shape returns a 400 on Opus 4.8, Opus 4.7, and Sonnet 5:

message = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=16000,
    thinking={"type": "adaptive"},
    output_config={"effort": "high"},  # low | medium | high | xhigh | max
    messages=[{"role": "user", "content": "Find the race condition in this code: ..."}],
)

The effort parameter (inside output_config) is the dial that replaced thinking budgets: it controls reasoning depth and overall token spend across five levels. In my testing, high (the default) is right for most work, xhigh pays off on hard coding and agentic tasks, and low is ideal for cheap subagent calls.

Structured outputs

When you need machine-parseable JSON, don’t beg for it in the prompt — constrain it. Passing a JSON Schema via output_config.format guarantees the response validates against your schema:

message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    output_config={
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"},
                    "plan": {"type": "string"}
                },
                "required": ["name", "email", "plan"],
                "additionalProperties": False
            }
        }
    },
    messages=[{"role": "user", "content": "Extract: John ([email protected]), Enterprise plan"}],
)

The related strict: true flag on tool definitions does the same for tool parameters. Between the two, I haven’t written a JSON-repair function in months.

Prompt caching

Prompt caching is the single biggest cost lever in the Claude API. Mark a stable prefix — a long system prompt, a document, tool definitions — with cache_control, and repeat requests read it at roughly 0.1× the input price. Writes cost 1.25× (5-minute TTL) or 2× (1-hour TTL), so the cache pays for itself after one or two hits:

message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": long_system_prompt,  # stable content first
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[{"role": "user", "content": user_question}],
)
# Verify: message.usage.cache_read_input_tokens should be nonzero on repeat calls

Caching is a prefix match — a timestamp interpolated into your system prompt silently invalidates everything after it. The full economics are covered in the Claude API pricing breakdown.

Message Batches API

Anything that doesn’t need a real-time answer belongs in a batch. You submit up to thousands of requests, results land within 24 hours (usually far faster in my experience), and both input and output tokens are billed at a 50% discount:

batch = client.messages.batches.create(
    requests=[
        {
            "custom_id": "doc-001",
            "params": {
                "model": "claude-haiku-4-5",
                "max_tokens": 512,
                "messages": [{"role": "user", "content": "Summarize: ..."}]
            }
        },
        # ... more requests
    ]
)
# Poll client.messages.batches.retrieve(batch.id) until processing_status == "ended",
# then stream client.messages.batches.results(batch.id) and key results by custom_id.

Tools: your functions and Anthropic’s

Tool use turns Claude from a text generator into an agent. You define tools with a name, description, and JSON Schema; Claude responds with tool_use blocks; you execute the function and return a tool_result. The SDKs ship a tool runner that automates that loop. On top of your own tools, Anthropic hosts server-side tools that run on their infrastructure with zero client code: web search ($10 per 1,000 searches), web fetch (free beyond token costs), and code execution in a sandboxed container. There’s also an MCP connector for calling remote Model Context Protocol servers directly from the Messages API, and a Files API for uploading documents once and referencing them across requests.

Rate limits and error handling

Every organization sits in a usage tier (1 through 4, then custom), and each tier caps requests per minute plus input and output tokens per minute, per model. Exceeding a limit returns a 429 with a retry-after header; the official SDKs honor it and retry automatically. The errors worth explicit handling in application code are 401 (bad key), 429 (back off), 400 (fix your request — this is where removed parameters like temperature show up), and 529 (API overloaded, retry with backoff). I’ve covered tier thresholds and monitoring headers in the Claude API rate limits guide.

What developers get wrong with the Claude API

  • Sending temperature to current models. Tutorials from 2024–2025 all set it. On Opus 4.7+, Sonnet 5, and Fable 5 it returns a 400. Delete it.
  • Using budget_tokens for thinking. Fixed thinking budgets are removed on current models. Use thinking: {"type": "adaptive"} plus effort.
  • Reading content[0].text unconditionally. With thinking or tool use enabled, the first block may not be a text block. Iterate and check block.type.
  • Not streaming long outputs. Non-streaming requests above roughly 16K max_tokens risk HTTP timeouts. Use the SDK’s stream() helper and get_final_message().
  • Ignoring the usage object. Teams discover their cost profile in the monthly invoice instead of their logs. Record input_tokens, output_tokens, and the cache fields per request.
  • Skipping prompt caching. If you send the same 5,000-token system prompt on every request at full price, you’re paying ten times more than necessary for that prefix.

Where to go from here

The fastest path to a working integration is the hands-on Claude API tutorial — install, authenticate, first call, streaming, and error handling in about twenty minutes. From there, the API section has language-specific guides and deep dives on pricing, rate limits, and cost estimation. Anthropic’s official documentation remains the canonical reference for request schemas.

FAQ

Is the Claude API free to use?

No. The Claude API is pay-as-you-go, billed per million tokens processed. New Console accounts receive a small amount of free credit for testing, but sustained usage requires adding billing. API access is separate from claude.ai subscriptions like Pro or Max.

What is the difference between the Claude API and claude.ai?

claude.ai is the consumer chat product with subscription pricing, while the Claude API is the developer interface billed per token. They use the same underlying models but have separate billing, separate limits, and separate feature surfaces. A Claude Pro subscription does not include API credits.

Which Claude model is best for API development?

Claude Sonnet 5 is the best default: near-Opus coding quality at $3 per million input tokens and $15 per million output tokens, with introductory pricing of $2 and $10 through August 31, 2026. Use Haiku 4.5 for high-volume simple tasks and Opus 4.8 for the hardest reasoning work.

Does the Claude API support streaming?

Yes. Set stream to true or use the SDK streaming helpers to receive the response as server-sent events. Streaming is recommended for any request with a large max_tokens value because it avoids HTTP timeouts and lets you render output as it generates.

Why does the API reject my temperature parameter?

The temperature, top_p, and top_k sampling parameters are removed on current models including Opus 4.8, Opus 4.7, and Sonnet 5, and sending them returns a 400 error. Remove the parameter and steer output style through prompting instead.

How large is the Claude API context window?

Current Opus and Sonnet models, including Opus 4.8 and Sonnet 5, offer a 1 million token context window at standard pricing. Claude Haiku 4.5 keeps a 200K token window. Maximum output is 128K tokens on Opus and Sonnet tiers and 64K on Haiku 4.5.

ClaudeAI.Guide Editorial Team

ClaudeAI.Guide Editorial Team

Independent editorial team behind ClaudeAI.Guide — an unofficial, third-party reference that is not affiliated with, endorsed by, or sponsored by Anthropic, PBC. We cover Anthropic’s Claude AI assistant from a practitioner’s perspective: hands-on tutorials, practical prompts, model comparisons (Claude Opus, Sonnet, Haiku), API walkthroughs, and honest reviews grounded in our own daily use. Everything we publish is tested in real workflows and verified at the time of writing, with no affiliate-driven hype. “Claude” and “Anthropic” are trademarks of Anthropic, PBC, used here for descriptive, nominative fair-use purposes only.

Articles: 72