Anthropic Claude API: The Complete Guide for AI Engineers (2026)
Everything you need to start building with the Anthropic Claude API — signup, API key, first call in 3 minutes. We cover every Claude model from Haiku 4.5 through Opus 4.8, extended thinking, effort levels, prompt caching, streaming, tool use, pricing, rate limits, common errors, and how to route Claude alongside other providers.
The Anthropic Claude API gives you programmatic access to the Claude model family — from the lightweight Haiku 4.5 through the frontier-class Opus 4.8. All models support text and image input, streaming, tool use, prompt caching, and extended thinking. You sign up at console.anthropic.com, grab an API key, point your HTTP client (or Anthropic SDK) at https://api.anthropic.com, and start building.
We wrote this guide because Anthropic's model lineup has expanded rapidly through 2025–2026 — Opus 4, 4.1, 4.5, 4.6, 4.7, 4.8, plus Sonnet 4, 4.5, 4.6, Haiku 4.5, and the new Fable 5 — and navigating which model to pick, how pricing works, what effort levels do, and how rate limit tiers interact can trip you up. This is the single reference we wanted when we first integrated Anthropic into our routing layer.
Getting Started in 3 Minutes
Step 1: Create an account. Go to console.anthropic.com and sign up. Anthropic supports email registration and Google OAuth.
Step 2: Get your API key. Navigate to Settings → API Keys and click "Create Key." Copy it immediately — keys are shown once. Store it securely (environment variable, secrets manager, never in code).
Step 3: Make your first call. Install the Anthropic Python SDK:
pip install --upgrade anthropic
Then run:
import anthropic
client = anthropic.Anthropic(
api_key="YOUR_ANTHROPIC_KEY",
)
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "What is Claude?"}],
)
print(message.content[0].text)
That's it. You'll land on the Start tier with a $500/month spend cap — enough to prototype and test.
Using the OpenAI SDK (Compatibility Mode)
If your codebase already uses the OpenAI Python SDK, Anthropic provides an OpenAI-compatible endpoint. Install the openai package and point it at Anthropic:
from openai import OpenAI
client = OpenAI(
api_key="YOUR_ANTHROPIC_KEY",
base_url="https://api.anthropic.com/v1/",
)
response = client.chat.completions.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "What is Claude?"}],
)
print(response.choices[0].message.content)
This is especially useful when you're routing between multiple providers — you can swap between Claude, OpenAI, and DeepSeek models by changing base_url and model, keeping the rest of your code identical.
All Claude Models Available via API
Anthropic's current model lineup spans three tiers: Opus (frontier intelligence), Sonnet (balanced performance), and Haiku (speed-optimized). Here is what's available as of June 2026:
| Model | API ID | Context | Max Output | Input Price | Output Price | Best For |
|---|---|---|---|---|---|---|
| Fable 5 | claude-fable-5 | 1M | 128K | $10/MTok | $50/MTok | Most demanding reasoning, long-horizon agents |
| Opus 4.8 | claude-opus-4-8 | 1M | 128K | $5/MTok | $25/MTok | Complex coding, autonomous agents, frontier tasks |
| Opus 4.7 | claude-opus-4-7 | 1M | 128K | $5/MTok | $25/MTok | Coding, agents, enterprise workflows |
| Opus 4.6 | claude-opus-4-6 | 1M | 128K | $5/MTok | $25/MTok | Coding, agents, enterprise workflows |
| Opus 4.5 | claude-opus-4-5 | 200K | 64K | $5/MTok | $25/MTok | Coding, agents, computer use |
| Sonnet 4.6 | claude-sonnet-4-6 | 1M | 64K | $3/MTok | $15/MTok | High-volume production, coding, agents |
| Sonnet 4.5 | claude-sonnet-4-5 | 1M | 64K | $3/MTok | $15/MTok | Production agents, coding, research |
| Haiku 4.5 | claude-haiku-4-5 | 200K | 8K | $1/MTok | $5/MTok | Sub-agents, real-time apps, free-tier products |
Key observations:
- Opus 4.7+ uses a new tokenizer that produces roughly 30% more tokens for the same text. Factor this into cost estimates when comparing against Opus 4.5 or Sonnet models.
- Opus 4.1 and earlier are deprecated or retired with significantly higher pricing ($15/$75 per MTok). Migrate to Opus 4.5+ if you're still using them.
- Fable 5 is the newest and most capable model, priced at $10/$50 per MTok. It uses adaptive thinking (always on) rather than manual extended thinking.
For model details including deprecation schedules, see Anthropic's model deprecations page. We also have a migration guide covering Anthropic's deprecation cadence.
Extended Thinking and Effort Levels
Extended thinking is what sets Claude apart from most competitors. It lets the model reason step-by-step before delivering a final answer — visible in the API response as a thinking content block.
How to Enable Extended Thinking
For Opus 4.5, Haiku 4.5, and earlier models, use manual budget_tokens:
message = client.messages.create(
model="claude-opus-4-5",
max_tokens=16384,
thinking={
"type": "enabled",
"budget_tokens": 10000,
},
messages=[{"role": "user", "content": "Solve this step by step: ..."}],
)
For Opus 4.6+, Sonnet 4.6, Opus 4.7, and Opus 4.8, use adaptive thinking with effort levels:
message = client.messages.create(
model="claude-opus-4-8",
max_tokens=16384,
thinking={"type": "adaptive"},
effort="high",
messages=[{"role": "user", "content": "Design a distributed cache system."}],
)
For Fable 5, adaptive thinking is always on — you cannot disable it. Use the effort parameter to control depth.
Effort Levels Explained
The effort parameter controls how many tokens Claude spends on reasoning:
| Level | Available On | Use Case |
|---|---|---|
max | Fable 5, Opus 4.8, 4.7, 4.6, Sonnet 4.6 | Deepest possible reasoning, most thorough analysis |
xhigh | Fable 5, Opus 4.8, 4.7 | Long-running agentic tasks (30+ minutes), multi-million token budgets |
high | All supported models | Default. Complex reasoning, difficult coding, agentic tasks |
medium | All supported models | Balance of speed, cost, and performance |
low | All supported models | Fastest, cheapest. Best for simple tasks and sub-agents |
Practical tip: For Sonnet 4.6, Anthropic recommends starting with medium effort as your default rather than high, since the model's default high effort can produce unnecessary latency for simpler requests.
Prompt Caching
Prompt caching is one of the most cost-effective features in the Claude API. It stores frequently used prompt prefixes (system instructions, documents, tool definitions) so subsequent calls only pay the cache-hit rate: 90% cheaper than base input pricing.
| Base Input | 5-min Cache Write | 1-hour Cache Write | Cache Hit | |
|---|---|---|---|---|
| Opus 4.x | $5/MTok | $6.25/MTok | $10/MTok | $0.50/MTok |
| Sonnet 4.x | $3/MTok | $3.75/MTok | $6/MTok | $0.30/MTok |
| Haiku 4.5 | $1/MTok | $1.25/MTok | $2/MTok | $0.10/MTok |
Two cache TTLs are available: 5-minute (cheaper write, shorter retention) and 1-hour (pricier write, longer retention). Choose based on your call frequency. For most production systems with consistent traffic, the 1-hour cache pays for itself quickly.
Rate limit bonus: For most Claude models, cached input tokens do not count toward your input tokens per minute (ITPM) rate limit. With an 80% cache hit rate, you can effectively process 5× more total input tokens than your raw ITPM limit suggests.
To enable caching, add cache_control breakpoints in your message content:
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
system=[
{
"type": "text",
"text": "You are an expert code reviewer...", # long system prompt
"cache_control": {"type": "ephemeral"},
}
],
messages=[{"role": "user", "content": "Review this PR: ..."}],
)
Streaming
All Claude models support streaming via server-sent events (SSE). Streaming is critical for user-facing applications — it reduces perceived latency and lets you show partial responses immediately:
with client.messages.stream(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Explain quantum computing."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
When using extended thinking with streaming, thinking blocks arrive first, followed by the text response. You can inspect or display thinking content in real time.
Tool Use (Function Calling)
Claude supports tool use (function calling) across all current models. You define tools in your API request, and Claude returns tool_use content blocks when it decides to call one:
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=[
{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
},
"required": ["city"],
},
}
],
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
)
When Claude returns a tool_use block, execute the function locally and send back a tool_result message to continue the conversation. Claude can chain multiple tool calls in a single turn, making it effective for agent workflows.
Rate Limits and Tiers
Anthropic uses a tier-based rate limit system. Your organization progresses through tiers as your usage and spend history grow:
| Tier | Monthly Spend Cap | How to Qualify |
|---|---|---|
| Start | $500 | Default on signup |
| Build | $1,000 | Usage history and spend growth |
| Scale | $200,000 | Significant consistent usage |
| Custom | No cap | Contact Anthropic sales |
Rate limits are measured in three dimensions: requests per minute (RPM), input tokens per minute (ITPM), and output tokens per minute (OTPM), each set per model class.
Recent change (June 2026): Anthropic unified rate limit tiers so that Sonnet, Opus, and Haiku share the same tier progression. Previously, different model classes could have asymmetric limits within the same tier. This simplification means your tier level now applies uniformly across all Claude models.
When you hit a rate limit, the API returns a 429 error with a retry-after header. Implement exponential backoff, or route overflow traffic to a backup provider.
Common Errors and Fixes
| Error Code | Meaning | Fix |
|---|---|---|
| 401 | Invalid API key | Check key in Console → Settings → API Keys. Regenerate if compromised. |
400 (invalid_request_error) | Malformed request | Check model ID spelling, max_tokens > 0, messages format. |
400 (thinking budget error) | budget_tokens used on Opus 4.7+ or Fable 5 | Switch to thinking: {"type": "adaptive"} with effort parameter. |
| 429 | Rate limit exceeded | Check retry-after header. Implement backoff. Consider tier upgrade. |
| 529 | API overloaded | Transient. Retry after a few seconds. |
| 413 | Request too large | Reduce input size or use prompt caching to stay within context limits. |
Tip for thinking-related errors: The API surface for thinking has evolved rapidly. Opus 4.7+, Opus 4.8, and Fable 5 no longer accept budget_tokens (returns 400). Use adaptive thinking with effort levels instead. Opus 4.5 and Haiku 4.5 still accept budget_tokens.
Production Checklist
Before going to production with the Claude API, verify these items:
- Use prompt caching for system prompts, tool definitions, and repeated context. The 90% cost reduction on cache hits is too significant to skip.
- Set explicit effort levels rather than relying on the default
high. For Sonnet 4.6, start withmedium; for Opus in agent loops, usehighorxhigh. - Implement streaming for user-facing responses to reduce perceived latency.
- Handle 429 errors with exponential backoff and optional fallback routing to another provider.
- Pin model versions (e.g.,
claude-sonnet-4-5not justclaude-sonnet) so your behavior doesn't change when Anthropic releases new versions. - Set
max_tokensappropriately. For agent workflows with extended thinking, leave headroom for thinking tokens — they count againstmax_tokenson legacy models (Opus 4.5, Haiku 4.5). - Monitor your tier. Check Settings → Limits to see your current tier and usage. Request upgrades proactively if you're approaching limits.
- Use the Messages API, not the legacy Completions API. The Messages API supports all current features (thinking, tools, caching, vision).
TheRouter Integration
If you're using TheRouter to route requests across multiple providers, Claude models are available through the Anthropic provider with automatic fallback. TheRouter routes OpenAI-compatible requests through configured providers, so you can access Claude alongside DeepSeek, DashScope, and others through a single endpoint.
Key benefits of routing Claude via TheRouter:
- Fallback routing: If Opus hits rate limits or returns errors, TheRouter can automatically route to a backup provider like SiliconFlow or Volcengine Ark.
- Unified billing: Track spend across Claude, OpenAI, DeepSeek, and Chinese providers through a single accounting surface.
- Model aliasing: Use consistent model names across your codebase while TheRouter handles the provider-specific mapping.
For a deeper look at fallback strategies, see our LLM API fallback routing guide.
FAQ
Q: Which Claude model should I use for coding?
Opus 4.8 is Anthropic's best coding model. If cost is a concern, Sonnet 4.6 at medium effort provides an excellent balance. For coding sub-agents, Haiku 4.5 is fast and cheap. See our coding agent model comparison for benchmarks.
Q: How does Claude pricing compare to OpenAI and DeepSeek? Claude Sonnet 4.5/4.6 at $3/$15 per MTok competes with GPT-5.5 at $2/$8 per MTok (OpenAI) and DeepSeek V4-Flash at $0.14/$0.28 per MTok. Opus 4.8 at $5/$25 is priced against GPT-5.5-Pro. DeepSeek remains the budget option; Claude competes on capability rather than price.
Q: Can I use Claude with the OpenAI SDK?
Yes. Anthropic provides an OpenAI-compatible endpoint. Change base_url to https://api.anthropic.com/v1/ and use your Anthropic API key. Some Anthropic-specific features (extended thinking with budget_tokens, prompt caching syntax) may not map 1:1.
Q: What's the difference between extended thinking and effort?
Extended thinking (budget_tokens) is the older mechanism — you manually set a thinking token budget. Effort is the newer, recommended approach for Opus 4.6+ and Sonnet 4.6 — a single parameter (low/medium/high/xhigh/max) that controls all token spend, including thinking. Fable 5 only supports effort.
Q: How do I avoid the 429 rate limit? Use prompt caching (cached tokens don't count toward ITPM), implement exponential backoff, and consider routing overflow to a fallback provider. If you consistently hit limits, request a tier upgrade through the Anthropic Console.
Sources: Anthropic pricing (retrieved 2026-06-29), Anthropic rate limits (retrieved 2026-06-29), Anthropic models overview (retrieved 2026-06-29), Anthropic extended thinking docs (retrieved 2026-06-29), Anthropic effort docs (retrieved 2026-06-29).