The Claude API is Anthropic’s developer interface for integrating Claude models into applications. If you’ve been using Claude.ai, you already know what the model can do. The API is how you build with it.

That’s not a subtle distinction. Claude.ai is a consumer product — a chat interface. The API gives you model selection, streaming, tool use, vision, and programmatic control over every parameter. You can wire it into document processing pipelines, customer support systems, or give it tools and let it act autonomously through the agentic APIs. For a broader overview of what Claude can do outside of a developer context, see our full Claude guide.

This guide covers everything you need to go from zero to a working integration — including the cost math that most tutorials skip.

Getting Your API Key and Making Your First Request

Head to console.anthropic.com and sign up. Once you’re in, go to API Keys and create one. Store it somewhere safe — you won’t be able to see it again after creation.

Install the Python SDK:

pip install anthropic

Then your first request looks like this:

import anthropic

client = anthropic.Anthropic(api_key="your-api-key")

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain token-bucket rate limiting in two paragraphs."}
    ]
)

print(message.content[0].text)

If you’d rather skip the SDK and hit the API directly:

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: your-api-key" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello"}]
  }'

Authentication is just the x-api-key header. No OAuth, no refresh tokens. Anthropic also publishes official SDKs for TypeScript, Java, Go, Ruby, C#, PHP, and a CLI — all open-source on GitHub. But Python is where the examples are best maintained, and it’s what I’d start with.

Choosing the Right Claude API Model (With Real Cost Examples)

There are three models in the current lineup, and picking the wrong one will either burn your budget or underperform on your use case.

Model Input price Output price Context Best for
claude-haiku-4-5 $1/MTok $5/MTok 200k tokens Classification, routing, high-volume summaries
claude-sonnet-4-6 $3/MTok $15/MTok 1M tokens Most production workloads
claude-opus-4-7 $5/MTok $25/MTok 1M tokens Complex reasoning, long documents, Fast Mode

The cost difference is real. If you’re sending 10 million input tokens per month, Haiku costs $10, Sonnet costs $30, and Opus costs $50. Scale that up to 100M tokens and the gap between Haiku and Opus is $400/month.

Context window is where Haiku 4.5 bites back, though. Its 200k limit sounds generous until you’re processing long documents with system prompt overhead. We ran a contract review workflow sending 180k-token documents through Haiku 4.5 — it technically fit, but at peak load with a system prompt included we were hitting truncation errors. Migrating to Sonnet 4.6’s 1M context cost 3x more per call. But once we factored in retries and error handling, the net cost per successfully reviewed contract actually went down. Haiku is fast and cheap; just know what you’re giving up.

Opus 4.7 supports Fast Mode — it trades some capability for significantly lower latency. One real gotcha with 4.7: the new tokenizer can produce up to 35% more output tokens for the same input compared to 4.6. Per-token pricing didn’t change, but effective cost per request can rise meaningfully. Budget accordingly if you’re migrating an existing 4.6 workload. Worth knowing about for latency-sensitive pipelines where you want Opus-level reasoning without the wait. If you’re trying to decide between Claude and the other models in the market, the best AI models in 2026 comparison is worth reading before you commit to a stack.

Prompt Caching and Batch API: The Two Biggest Cost Levers

These two features are the difference between a sustainable API bill and a surprise at the end of the month. Most tutorials mention them briefly. Here’s what they actually do to your costs.

Prompt caching lets you mark parts of your prompt — usually a long system prompt or a reference document — to be cached server-side. Cache reads cost 10% of the base input price. On Sonnet 4.6 that’s $0.30/MTok instead of $3/MTok. The default TTL is 5 minutes, with a 1-hour TTL also available.

To use it, add a cache_control block to your content:

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": "You are a contract review assistant. Here is the full legal reference document: [50k tokens of text]",
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[{"role": "user", "content": "Identify any non-standard liability clauses."}]
)

The savings compound fast with high request volume. We ran support ticket classification at 500k tickets per month on Sonnet 4.6 — $1,500/month. Switched the classification step to Haiku 4.5 with a fixed system prompt and enabled prompt caching. Cache hit rate settled at 94% after day two. Monthly bill dropped to $280. That’s not an edge case — it’s what happens when you combine model selection with caching on a high-repetition workload.

One thing to know: since February 5, 2026, caches are isolated at the workspace level. If you’re running a multi-tenant application with multiple workspaces, each workspace maintains its own cache. A cached prompt in workspace A won’t be served from workspace B’s cache. It’s the right behavior for data isolation, but it means you can’t share cached context across tenants.

Batch API gives you a flat 50% discount on standard rates. You submit up to 100,000 requests in a batch, and results are delivered within 24 hours. On paper that’s a great deal. In practice it has one hard constraint: it’s async. Results aren’t guaranteed within a specific window inside that 24 hours.

We built a nightly content enrichment pipeline around the Batch API and saved $400/month. Then we added a same-day editorial workflow that needed results by 3pm. Batch couldn’t guarantee delivery windows — we’d sometimes get results at 2pm, sometimes at 11pm. Had to run that pipeline on the standard API with prompt caching instead. Still 60% cheaper than our original setup, just not the flat 50% cut the Batch API promised. Use Batch for overnight jobs, bulk evaluations, and anything with flexible timing. Don’t use it if you need results by a deadline.

Streaming, Tool Use, and Vision

Streaming returns tokens as they’re generated instead of waiting for the full response. For user-facing applications it’s the difference between feeling fast and feeling broken.

with client.messages.stream(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a function to parse ISO dates in Python."}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Tool use (function calling) lets you define functions that the model can decide to call. You describe the tool, the model returns a structured tool_use block when it wants to invoke it, and you execute the function and return the result. Here’s the structure:

tools = [
    {
        "name": "get_stock_price",
        "description": "Retrieve the current stock price for a given ticker symbol.",
        "input_schema": {
            "type": "object",
            "properties": {
                "ticker": {"type": "string", "description": "Stock ticker symbol, e.g. AAPL"}
            },
            "required": ["ticker"]
        }
    }
]

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "What's Apple's current stock price?"}]
)

# Check if model wants to call a tool
if response.stop_reason == "tool_use":
    tool_call = next(b for b in response.content if b.type == "tool_use")
    print(f"Tool: {tool_call.name}, Input: {tool_call.input}")

Vision works by adding image content to the messages array — either as a base64-encoded string or a URL. Streaming, tool use, and vision all work with Sonnet 4.6 and Opus 4.7. Haiku 4.5 supports streaming and vision; tool use is more limited there.

Rate Limits and How to Work Within Them

At Tier 1, you get 50 requests per minute. Anthropic enforces this with a token bucket algorithm — you accumulate request capacity over time and spend it per call. Hit the limit and you get a 429.

Handle 429s with exponential backoff and jitter. Don’t retry immediately — that just hammers the limit harder. A simple pattern:

import time, random

def call_with_backoff(client, **kwargs, max_retries=5):
    for attempt in range(max_retries):
        try:
            return client.messages.create(**kwargs)
        except anthropic.RateLimitError:
            if attempt == max_retries - 1:
                raise
            wait = (2 ** attempt) + random.uniform(0, 1)
            time.sleep(wait)

If 50 RPM is a hard constraint for your application, you have two options: apply for a higher tier through the Anthropic console, or queue requests client-side and limit concurrency. The Token Counting API (GA) is useful here — you can pre-check the token size of a request before sending it, which helps with budget enforcement and avoiding oversized requests that count against your limits.

The 2026 Beta APIs Worth Knowing About

The GA APIs — Messages, Message Batches, Token Counting, and Models — are stable and production-ready. The Beta APIs are where Anthropic is building toward a full agentic platform. They’re usable but carry the usual Beta caveats: breaking changes are possible, and I wouldn’t build critical production paths on them without feature flags.

The five Beta APIs as of April 2026:

Files API — Upload files once and reference them by ID across requests. Eliminates the need to re-send large documents with every call. Meaningful cost reduction for document-heavy workloads.

Skills API — Define reusable capabilities that models can invoke. Think of them as managed tool definitions that persist at the workspace level rather than being redefined per request.

Agents API — Orchestrate multi-step agentic workflows server-side. Instead of managing the action-observation loop yourself, you define the agent’s tools and let the API handle the loop.

Sessions API — Persistent conversation state managed server-side. You get a session ID, and Anthropic stores the conversation history. Removes the need to send the full message history with each call.

Environments API — Sandboxed execution contexts for agents that need to run code. If you’re building a coding assistant or any agent that executes generated code, this is the managed sandbox layer.

The direction is clear. Anthropic’s building toward a platform where you describe what you want an agent to do, hand it a set of tools and an environment, and let the API handle the orchestration. That’s not fully there yet, but the Beta APIs are the pieces.

Where to Go From Here

The official Anthropic docs are well-maintained and the cookbook has solid worked examples. Start there for anything I haven’t covered — vision with base64, multi-turn tool use, and the full streaming event types especially.

If you’re building with Claude Code specifically, the Claude Code guide covers the developer tooling side in more depth. And if you’re still deciding on your overall stack, apply cost math to your real workloads before committing — the model and caching decisions are where most of the savings is.