AI Turnpoint Logo

The Anthropic API, From First Key to Production Traffic

A practical Anthropic API guide for teams: API keys and keyless auth, the Messages API, model choice, tool use, prompt caching, rate limits and 429 fixes.

Updated 15 min read
Laptop on a desk showing code in a dark editor, next to a small potted succulent

The Anthropic API (officially the Claude API) is a REST API at api.anthropic.com that gives your code access to Claude models through the Messages API, plus batch, token counting, files and Claude Managed Agents endpoints. You need a Claude Console account and an API key, and requests now pin API version 2026-10-21.

This guide is for engineers and founders putting Claude into a product. It covers the credential choices most tutorials skip, the version change that breaks older sampling code, and the rate limit mechanics that decide whether your app survives a traffic spike.

Key Takeaways

  • Every request needs an API key (or a short-lived federated token), an anthropic-version header and a JSON body with model, max_tokens and messages
  • API version 2026-10-21 removed sampling parameters temperature, top_p and top_k; sending any of them now returns a 400 error on every model
  • Start on Claude Opus 5.5 for most workloads, as Anthropic recommends, and move up to Fable 5.2 or down to Sonnet 5.5 and Haiku 5.5 after you run evals
  • Cached input reads do not count toward input-token rate limits, so prompt caching raises throughput as well as cutting cost
  • A monthly spend-cap 429 has no retry-after header and no retry loop will fix it; plan tier increases before launch

What Is the Anthropic API?

The Claude API overview page in Anthropic's developer docs, listing the base URL, prerequisites and available APIs

The Anthropic API is the first-party way to call Claude from your own software. Anthropic's docs call it the Claude API, and both names point at the same service: a RESTful API at api.anthropic.com that serves Claude models and Claude Managed Agents.

The generally available surface is small. The API overview lists six APIs: Messages (POST /v1/messages), Message Batches, Token Counting, Models, Files and Skills. Agents, Sessions and Environments for Managed Agents are in beta.

Most products only ever touch the Messages API. It is stateless, which means you send the full conversation history on every request, and Claude returns one assistant message with a stop_reason and token usage.

Why the Anthropic API Matters for Product Teams

The main reason is capability per request. Every current Claude model has a 1M token context window and 128K tokens of maximum output, so a single call can read a full codebase module or a long contract. That changes how you design retrieval, which we cover in our RAG guide.

The first-party API is also where Anthropic promises direct access to the latest models and features, which matters if you want new capabilities on launch day.

How the Anthropic API Works: Five Building Blocks

A production integration comes down to five decisions: how you authenticate, how you shape a request, which model you call, which features you turn on, and how you handle limits and errors. The rest of this guide walks through each one.

Block 1: Credentials and Headers

Every request carries four headers, per the overview. Authorization: Bearer <token> holds your API key or a federated token, anthropic-version pins the API version, and content-type is application/json. The older x-api-key header is a legacy fallback that still works.

A fifth header, anthropic-workspace-id, is required when your key is not scoped to a single workspace. Keys created for one workspace run there automatically.

Block 2: The Request Shape

A minimal Messages API call has three required fields: model, max_tokens and messages. Here is the official first call from Anthropic's quickstart, sent with an API key:

Shell
curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1000,
    "messages": [
      {
        "role": "user",
        "content": "What should I search for to find the latest developments in renewable energy?"
      }
    ]
  }'

The response is a message object with a content array of blocks, a stop_reason such as end_turn, and a usage object with input_tokens and output_tokens. Log usage from day one. It costs nothing to record, and it feeds the LLM observability stack you will want later.

Block 3: Models

Model choice is a string in the request. Anthropic's current lineup, from its models overview and November release notes, looks like this:

Model

API ID

Best for

Input / output per MTok

Claude Fable 5.2

claude-fable-5-2

Demanding reasoning, long-horizon agents

$8 / $40

Claude Opus 5.5

claude-opus-5-5

Default for most workloads, agentic coding

$4 / $20

Claude Sonnet 5.5

claude-sonnet-5-5

Speed plus intelligence

$2 / $10

Claude Haiku 5.5

claude-haiku-5-5

High-volume, latency-sensitive tasks

From $0.10 / $0.50

Fable 5.2 shipped on November 9, 2026. Anthropic's launch post still tells most users to start with Opus 5.5 and switch up or down by task.

You can also query GET /v1/models to read each model's token limits and capabilities programmatically, which beats hardcoding limits in config.

Block 4: Features You Opt Into

Tool use, structured outputs, prompt caching and streaming are request-level fields on the same Messages endpoint, and batches wrap ordinary Messages requests. The deep-dive sections below cover the ones that change architecture.

Block 5: Limits and Errors

Rate limits are set per organization, by usage tier, and measured in requests per minute (RPM), input tokens per minute (ITPM) and output tokens per minute (OTPM). The rate limits page explains that capacity refills continuously with a token bucket rather than resetting each minute. We cover the failure modes in the reliability section.

Getting an Anthropic API Key (and When Not to Use One)

The fastest path is three steps. Create a key on the API keys page of the Console, export it, and install an SDK:

Shell
export ANTHROPIC_API_KEY="your-api-key-here"
pip install anthropic
npm install @anthropic-ai/sdk

The official SDKs read ANTHROPIC_API_KEY automatically and send the auth, version and content-type headers for you. Anthropic maintains client SDKs for Python, TypeScript, C#, Go, Java, PHP and Ruby.

Pick the Right Key Type

When you create a key, you now choose what it acts as. Anthropic's authentication docs define three types:

Credential

Acts as

Use it for

Personal key

You, with your roles

Local development and experiments

Service account key

A service account

Shared services, CI, backend jobs

Workspace key (legacy)

The workspace

Existing setups only; Anthropic recommends migrating

Workload Identity Federation

A federated workload, no stored key

Cloud workloads with an identity provider

Linked billing (beta)

Your app, billed to the customer's org

Products where customers pay for their own Claude usage

Personal and service account keys are identity-backed. When the person or service account leaves the organization, the key stops working, which is exactly what you want when an employee departs.

Set an Expiration

Keys take an expiration at creation: presets of 3 hours, 1 day, 7 days or 30 days, a custom duration, or Never for keys you rotate yourself from a secrets manager. An expired key returns a 401 authentication_error and cannot be reactivated, so build rotation before the first expiry email arrives.

Skip Keys Entirely With Workload Identity Federation

Workload Identity Federation swaps a JWT from your identity provider for a short-lived Anthropic token. Token lifetimes run from 60 to 86,400 seconds, with a default of 3,600, and the SDK refreshes the token before it expires.

For a backend on a major cloud, this removes the long-lived secret that most API key leaks start from. Your client is constructed with no API key at all.

Let Customers Pay With Linked Billing

On November 17, 2026 Anthropic launched Linked billing in beta. A customer links their Claude organization to your app through OAuth, and you set billing_policy on each request to choose who pays.

"Anthropic just killed API keys... FINALLY!" developer Daniel San wrote on X, pointing out that users connect through OAuth with "No API keys to share." Keep in mind that requests still run in your organization, so your rate limits apply, and the feature is a beta service.

Tool Use and Structured Outputs: Making Claude Act

Tool use is how Claude calls functions. Anthropic's tool use overview splits tools by where the code runs, and that split shapes your architecture.

Client Tools Run in Your App

You define a tool with a name, a description and an input_schema (JSON Schema). When Claude decides to call it, the response has stop_reason: "tool_use" and one or more tool_use blocks. Your code runs the function and sends the output back in a tool_result block on the next request.

Text
{
  "name": "get_weather",
  "description": "Get the current weather for a given location.",
  "input_schema": {
    "type": "object",
    "properties": {
      "location": {
        "type": "string",
        "description": "City and state, e.g. San Francisco, CA"
      }
    },
    "required": ["location"]
  }
}

This request, run, return loop is the core of every agent. If you want the same tools available across many apps, the MCP connector lets the Messages API talk to remote MCP servers without running your own MCP client.

Server Tools Run on Anthropic's Infrastructure

Server tools such as web_search, web_fetch, code_execution and tool_search execute on Anthropic's side, and you see results in the same response. They save you from hosting a search proxy or a sandbox, at the cost of less control over what runs.

Structured Outputs Replace Prefill Tricks

Older code forced JSON by prefilling the start of Claude's reply. Prefill is not supported on Claude 4.6 and later models and returns a 400 error.

Use structured outputs instead: send a JSON Schema in output_config.format with type: "json_schema", or set strict: true on a tool to guarantee valid tool names and inputs. The Python SDK's client.messages.parse() accepts a Pydantic model and validates the response for you.

Prompt Caching and Batches: Cutting Latency and Cost

Prompt caching is the single biggest lever on a busy Claude integration. Add cache_control and the API reuses a processed prompt prefix instead of reading it again.

How Caching Works

The prompt caching docs offer two modes. Automatic caching takes one top-level cache_control field and moves the breakpoint to the last cacheable block as a conversation grows. Explicit caching puts cache_control on individual blocks, with up to 4 breakpoints.

Shell
curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1024,
    "cache_control": {"type": "ephemeral"},
    "system": "You are a helpful assistant that remembers our conversation.",
    "messages": [
      {"role": "user", "content": "My name is Alex. I work on machine learning."},
      {"role": "assistant", "content": "Nice to meet you, Alex! How can I help with your ML work today?"},
      {"role": "user", "content": "What did I say I work on?"}
    ]
  }'

The cache covers tools, system and messages in that order. Entries live 5 minutes by default and refresh for free each time they are used; a 1-hour TTL costs more to write.

The Rules That Decide Whether Caching Fires

Three rules trip teams up. First, prompts below the minimum length are silently not cached: 512 tokens on the Claude 5.x models, and up to 4,096 tokens on some older models. Check cache_creation_input_tokens and cache_read_input_tokens in usage; if both are 0, nothing was cached.

Second, any change earlier in the prefix invalidates everything after it. A September 2026 r/ClaudeAI comment on Claude Code reported that even changing effort mid-session invalidates the prompt cache.

Third, the pricing multipliers favor stable prefixes. Cache writes cost 1.25 times the base input price for a 5-minute TTL and 2 times for 1 hour, while reads cost 0.1 times base, or 0.05 times on Opus 5.5 and Sonnet 5.5.

Caching Raises Your Rate Limit Too

On the Claude API, cached reads do not count toward your ITPM limit.

Anthropic's own example: with a 2,000,000 ITPM limit and an 80 percent cache hit rate, you can process 10,000,000 input tokens per minute. If you are hitting 429s on a long system prompt or a shared document, caching it may solve the limit without a tier upgrade.

Batches for Work That Can Wait

The Message Batches API runs requests asynchronously at 50 percent of standard prices. A batch holds up to 100,000 requests or 256 MB, most finish within an hour, and a batch expires if it is not done in 24 hours.

Results stay downloadable for 29 days. Batches also skip ramp limits, which makes them the right home for nightly evals, backfills and bulk classification.

Rate Limits, Errors and Reliability

The Claude API rate limits documentation page explaining usage tiers and spend limits

A Claude feature that works in staging can still fail at launch. The usual causes are spend caps, per-minute limits, ramp limits and a short list of error codes.

Spend Caps and Tiers

Each tier carries a monthly spend cap: $500 on Start, $1,000 on Build and $200,000 on Scale, with Custom arranged by contract. New organizations can start in an Evaluation tier with lower limits that rise as usage history builds.

When you hit the cap, usage pauses until 00:00 UTC on the first of the next month. The API returns a 429 rate_limit_error with no retry-after header, and retries, including the SDK's, keep failing until access resumes or you move up a tier.

Per-Minute Limits

On the Start tier, Opus 5.5, Sonnet 5.5 and Haiku 5.5 each allow 4,000 RPM, 2,000,000 ITPM and 400,000 OTPM, while Fable 5.2 allows 500,000 ITPM and 100,000 OTPM. OTPM counts tokens actually generated, so a high max_tokens value costs you nothing against the limit.

Ramp limits are the newer trap. After a sharp jump in usage, requests can return 429 even under your limits, with error.details.error_code set to ramp_limit_exceeded; wait the retry-after seconds and grow traffic gradually.

Error Codes Worth Handling

Status

Type

What to do

400

invalid_request_error

Fix the request; also returned when you hit a spend limit you set

401

authentication_error

Key is malformed, revoked or expired; rotate it

403

permission_error

Check workspace and organization access

413

request_too_large

Messages requests are capped at 128 MB

429

rate_limit_error

Honor retry-after; if absent, check spend caps

500

api_error

Retry with exponential backoff

529

overloaded_error

API is temporarily overloaded; back off and retry

Every response carries a request-id header, and the Python and TypeScript SDKs expose it as _request_id. Log it with every failure; support asks for it first.

Retries, Backpressure and Timeouts

The official SDKs retry connection errors, 429s and 5xx errors twice by default with exponential backoff, honoring retry-after. That covers blips, not sustained load.

For sustained load, cap concurrency. "Using a concurrency cap will guard you against the 429s more than a backoff schedule," one developer noted on r/LLMDevs. A queue that defers jobs by the retry-after value spends no retry attempts while it waits.

Long generations need streaming. The SDKs check that non-streaming requests are not expected to exceed a 10-minute timeout, and Anthropic recommends streaming or batches for long-running requests.

Watch Status and Changelogs

Check Claude status during incidents, and read the release notes before every SDK upgrade. Pin model IDs in config so a model change is a deliberate deploy, not a surprise.

Claude API Versus Cloud Platforms

You can also reach Claude through cloud providers. The overview lists Anthropic-operated platforms: Claude Platform on AWS, Claude Models on Google Cloud (Anthropic managed) and Microsoft Foundry. Partner-operated options are Claude Models on Google Cloud (Google managed) and Amazon Bedrock.

Option

Billing and IAM

Feature timing

Choose it when

Claude API

Anthropic billing, Console keys or WIF

Newest models and features first

New products, full feature access

Anthropic-operated cloud

Cloud billing, cloud credentials

Varies by platform

You want cloud billing on an Anthropic-run service

Partner-operated cloud

Cloud billing and IAM

Varies by platform

Existing cloud commitments, compliance needs

Model IDs mostly match across platforms; Bedrock prefixes them, as in anthropic.claude-opus-5-5. Check each platform's page before you commit, because Anthropic says feature availability and timing differ by platform.

If your team already runs on OpenAI, Anthropic's OpenAI SDK compatibility lets you point the OpenAI client at https://api.anthropic.com/v1/ with a Claude key to test models quickly. For a side-by-side of the two APIs, see our OpenAI API guide and the Claude vs ChatGPT comparison.

Common Anthropic API Mistakes to Avoid

Sending Sampling Parameters on the New Version

API version 2026-10-21 removed temperature, top_p and top_k, and any request that sends them returns a 400 on every model. Strip them before upgrading to Python SDK 2.0.0 or TypeScript SDK 1.0.0, the first majors on the new version per the migration guide, and steer output with prompts and structured outputs instead.

Treating Every 429 as Transient

Retrying a spend-cap 429 just burns time until the first of the month. Branch on the retry-after header: present means wait, absent means check your spend cap or set limits in the Console.

Caching a Prompt That Changes Up Front

Putting a timestamp or user ID at the top of the system prompt invalidates the cache on every request. Keep stable content first, variable content last, and verify hits in usage.

Shipping a Never-Expiring Personal Key to Production

A personal key dies when its owner leaves the organization and leaks along with a laptop. Use a service account key from a secrets manager, or Workload Identity Federation, for anything that serves customers.

Upgrading Models Without Evals

Behavior shifts between versions. An auto-generated summary of a 400-comment r/ClaudeAI thread reported users, from Max subscribers to API developers, calling Opus 4.7 a significant downgrade from Opus 4.6. Pin IDs and run your own prompt evals before switching.

The Anthropic API in Practice: Shrinking Agent Requests With Message Threads

Agent loops resend the whole conversation on every turn because the Messages API is stateless. Anthropic's message threads beta, launched November 2, 2026 with the message-threads-2026-08-12 header, keeps the conversation on the server so each later request sends only new messages.

Satya Mallick measured the effect on a Claude agent solving a maze. "Our Claude maze agent was sending 9.8 MB per request by move 100. With the new message threads beta it sent 104 KB," he wrote on LinkedIn, adding that token counts stayed the same.

The trade-off is durability. A thread expires 5 minutes after its last request and is deleted no more than an hour after its last use, and a continue request returns 404 when the API can no longer continue it. Keep your own copy of the history so you can rebuild the conversation when that happens.

Frequently Asked Questions

Related Articles