You search for a Claude API tutorial, copy the first code sample, and get a 400 error. Or the pricing table is off by 5x. Or the rate limits it quotes do not exist anymore.
That is not bad luck. Anthropic's model line-up moves fast, and many tutorials were written for an older one. We read the current Anthropic documentation and 7 third-party guides, 19 sources in all, and checked every number against the official pages. This guide shows you how to get a key, make your first request, estimate the real bill, and avoid the errors that catch new users.
What the Claude API is, in plain words#
The Claude API lets your own app talk to Anthropic's Claude models. You send a list of messages to one web address, https://api.anthropic.com/v1/messages, and you get Claude's reply back as JSON. Anthropic calls this the Messages API, and almost everything else (tools, images, caching, batches) is an extra feature of that one endpoint.
A few ideas to know before you start:
- Token: a small chunk of text, roughly three-quarters of a word. You are billed per token, not per request.
- Input and output: what you send is input, what Claude writes back is output. Output is priced higher.
- Stateless: the API does not remember earlier turns. Your app sends the whole conversation each time.
- Model ID: a short string such as
claude-sonnet-5-5that picks which Claude answers.
If you are new to web APIs in general, our plain-English guide to what a REST API is covers the basics first.
Step 1: Get an API key#
- Create an account in the Claude Console (platform.claude.com).
- Go to the API keys page and click Create key.
- Name the key and choose an expiration. Anthropic offers presets of 3 hours, 1 day, 7 days or 30 days, a custom length, or Never.
- Copy the key immediately. Zapier's guide warns that you cannot view it again once the pop-up closes.
Anthropic's authentication page describes two kinds of key you will actually use. A personal key acts as you and stops working if you leave the organization. A service account key belongs to a workload, such as a production server, and is the better choice for anything shared. Older workspace keys still work but Anthropic calls them legacy.
On billing, Zapier's guide says the API is prepaid and pay-as-you-go, with a $5 minimum purchase, and that unused credits expire after one year. We could not find that exact wording on Anthropic's own pages, so check the Billing page in the Console before you load money.
Step 2: Make your first request#
Set the key as an environment variable. The official SDKs read it automatically, which keeps the key out of your code.
export ANTHROPIC_API_KEY="your-api-key-here"Install the Python package and save this as quickstart.py. It is Anthropic's own quickstart example.
python3 -m venv .venv && source .venv/bin/activate
pip install anthropicimport anthropic
client = anthropic.Anthropic()
message = client.messages.create(
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?",
}
],
)
for block in message.content:
if block.type == "text":
print(block.text)If you prefer plain HTTP, the same call in curl needs three headers: your key, an API version, and a content type.
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1000,
"messages": [{"role": "user", "content": "Say hello in one sentence."}]
}'Anthropic's authentication page also says Authorization: Bearer <key> works, and that the older x-api-key header is still supported. Either is fine.
How to read the reply#
The reply has a few fields worth knowing:
content: a list of blocks. Loop through it and print the ones whosetypeistext, as the example does. Newer models can also returnthinkingblocks, so never assume the first block is the answer.stop_reason:end_turnmeans Claude finished.max_tokensmeans your limit cut the answer short, so raise it.usage: how many input and output tokens you were billed for. Log it from day one.idand therequest-idheader: send these to Anthropic support if something breaks.
Which Claude model should you pick?#
Anthropic's models page lists four current models. All four accept text and images, support tools, have a 1 million token context window and can write up to 128,000 tokens in one reply.
| Claude Fable 5.1 | Claude Opus 5.5 | Claude Sonnet 5.5 | Claude Haiku 5.5 | |
|---|---|---|---|---|
| Model ID | claude-fable-5-1 | claude-opus-5-5 | claude-sonnet-5-5 | claude-haiku-5-5 |
| Anthropic's description | Demanding reasoning, long agent work | Long agentic coding and knowledge work | Best mix of speed and intelligence | High-volume, fast jobs |
| Input price per million tokens | $10 | $4 | $2 | $0.10 |
| Output price per million tokens | $50 | $20 | $10 | $0.50 |
| Speed | Slower | Moderate | Fast | Fastest |
| Default effort | high | medium | high | medium |
| Retirement | Not before 1 Sep 2027 | Not before 22 Sep 2027 | Not before 28 Sep 2027 | Not before 7 Oct 2027 |
Two details trip people up:
- Haiku 5.5's low price applies to prompts up to 100,000 tokens. Above that, input is $0.50 and output is $2.50 per million.
- Anthropic's own advice is to start with Opus 5.5 for most workloads, move up to Fable 5.1 only if your tests on Opus at higher effort still fall short, and move down to Sonnet or Haiku when speed and cost matter more.
Older models such as Claude Sonnet 4.6 and Haiku 4.5 are still available but are listed as legacy. Every Claude model ID is a pinned snapshot, so a model will not silently change under you.
Why old tutorial code breaks on current models#
This is the section most guides skip. Anthropic's errors page lists several settings that used to work and now return a 400 invalid_request_error on the newer models.
| Old tutorial habit | What happens now | What to do |
|---|---|---|
Pre-fill the start of Claude's answer (a final assistant message) | 400 on Claude 4.6 and later | Use structured outputs or tell Claude the format in the prompt |
thinking: {"type": "enabled", "budget_tokens": 5000} | 400 on Claude 4.7 and later | Omit thinking, or use {"type": "adaptive"}, and control depth with effort |
thinking: {"type": "disabled"} | 400 on Fable 5.1 and Opus 5.5, where thinking is always on | Lower the effort setting instead |
Forcing a tool with tool_choice set to any or a named tool | 400 on Fable 5.1, Opus 5.5 and Sonnet 5.5 | Use auto and say in the prompt which tool to use |
Copying an old model ID such as claude-3-5-sonnet-20241022 | Old IDs belong to retired models | Take the ID from the models page |
Two quieter changes also affect your bill. First, Claude 4.7 and later use a newer tokenizer that produces about 30% more tokens for the same text, so a prompt you measured on an older model will cost more. Recount with the model you plan to use. Second, Opus 5.5 defaults to a medium effort level, one step below some earlier models, so set effort yourself if quality looks lower than you expected.
How pricing works, with a real example#
Your cost for one request is simple:
cost = input tokens x input price + output tokens x output price
Prices are per million tokens. Take a typical chat reply: 2,000 tokens in and 500 tokens out. We ran the sums with a short Python script (it is pure arithmetic, so it needs no API key):
| Model | Cost per request | 1,000 requests per day | Over 30 days |
|---|---|---|---|
| Claude Fable 5.1 | $0.045 | $45.00 | $1,350.00 |
| Claude Opus 5.5 | $0.018 | $18.00 | $540.00 |
| Claude Sonnet 5.5 | $0.009 | $9.00 | $270.00 |
| Claude Haiku 5.5 | $0.00045 | $0.45 | $13.50 |
The spread is the point: the same traffic costs $13.50 or $1,350 a month depending on the model. That is why you test a cheaper model first.
Count tokens before you send#
Anthropic offers a token counting endpoint that is free to use, with its own rate limit of 5,000 requests per minute on the Start tier. It returns an estimate of the input tokens for a message, so you can price a prompt before you pay for it. Counting uses the tokenizer of the model you name, so pass the model you will really use.
import anthropic
client = anthropic.Anthropic()
response = client.messages.count_tokens(
model="claude-opus-5-5",
system="You are a scientist",
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(response.json())Three ways to cut the bill#
1. Prompt caching#
If every request starts with the same long text (a big system prompt, a document, a list of tools), you can ask Anthropic to cache it. The cached part is then read at a small fraction of the normal price.
From Anthropic's caching and pricing pages:
- A cache write costs 1.25x the normal input price for the default 5-minute cache, or 2x for a 1-hour cache.
- A cache read costs 0.1x the normal input price on most models. On Opus 5.5 and Sonnet 5.5 it is 0.05x, and on Fable 5.1 it is 0.025x.
- The cache lasts 5 minutes by default and is refreshed each time it is used.
- A prompt must be long enough to cache. For the current models the minimum is 512 tokens. Shorter prompts are processed normally with no error, which is a common reason caching "does nothing".
- You can switch it on with one top-level field,
cache_control: {"type": "ephemeral"}.
Worked example on Claude Sonnet 5.5: a 10,000-token system prompt sent with 1,000 requests. Without caching you pay for the prompt 1,000 times: $20.00. With a 5-minute cache you pay one write ($0.025) and 999 reads at $0.10 per million, about $1.02 for the prompt part. The question text and the answers are billed as normal on top.
To check that caching works, read usage.cache_read_input_tokens in the response. If both cache_creation_input_tokens and cache_read_input_tokens are zero, nothing was cached. A bonus: on most models, cached reads do not count toward your input-tokens-per-minute limit.
2. The Batch API#
If you do not need answers instantly, send requests as a batch. Anthropic charges 50% of the normal price for input and output.
- One batch can hold up to 100,000 requests or 256 MB, whichever comes first.
- Most batches finish within an hour, and every batch expires if not done within 24 hours.
- Results stay available for 29 days after creation.
- Batch discounts and caching discounts can stack. Anthropic suggests the 1-hour cache for batches, since they can take longer than 5 minutes.
For our 1,000 requests of 2,000 in and 500 out, batch pricing drops Opus 5.5 from $18.00 to $9.00 and Sonnet 5.5 from $9.00 to $4.50. It suits overnight jobs like tagging a backlog or running evaluations, not live chat.
3. Pick the cheapest model that passes your test#
Write 20 to 50 real examples of what your app will see. Run them on Haiku 5.5, then Sonnet 5.5, then Opus 5.5, and stop at the first model whose answers are good enough. Changing the model is a one-line edit, and the savings are the biggest of the three.
Rate limits explained#
Anthropic limits two different things.
Spend limits cap how much your organization can spend each calendar month:
| Usage tier | Monthly spend cap |
|---|---|
| Start | $500 |
| Build | $1,000 |
| Scale | $200,000 |
A Custom tier, arranged with Anthropic's team, has no monthly cap. You can also set your own lower limit on the Billing page.
Rate limits cap how fast you can send. They are measured per minute in three ways: requests (RPM), input tokens (ITPM) and output tokens (OTPM). Exceed any one and you get a 429. These are the standard limits from Anthropic's rate limits page:
| Tier | Model | RPM | ITPM | OTPM |
|---|---|---|---|---|
| Start | Opus 5.5, Sonnet 5.5, Haiku 5.5 | 1,000 | 2,000,000 | 400,000 |
| Start | Fable 5.x | 1,000 | 500,000 | 100,000 |
| Build | Opus 5.5, Sonnet 5.5, Haiku 5.5 | 5,000 | 5,000,000 | 1,000,000 |
| Build | Fable 5.x | 2,000 | 1,500,000 | 300,000 |
| Scale | Opus 5.5, Sonnet 5.5, Haiku 5.5 | 10,000 | 10,000,000 | 2,000,000 |
| Scale | Fable 5.x | 4,000 | 4,000,000 | 800,000 |
Things worth knowing:
- Tiers move automatically. Anthropic says organizations are placed on a tier from usage history and account standing and move up over time. New organizations may start in an Evaluation tier with limits below the table above. Your real numbers are on the Rate limits page in the Console.
- It is a token bucket. Capacity refills continuously instead of resetting on the minute, and a rate of 60 per minute may be enforced as 1 per second. A short burst can fail even if your per-minute total looks fine.
- Cache helps. For most models only uncached input counts toward ITPM, so a good cache raises your effective throughput.
max_tokensis free of limit math. OTPM counts only the tokens actually generated, so a highmax_tokensdoes not hurt.- Sharp spikes can trigger "acceleration limits". Ramp traffic up gradually.
- Fable limits are combined. One limit covers Fable 5.1 and Fable 5 together.
Some tutorials quote a "Tier 1 to Tier 4" table with figures like 50 requests per minute. The current documentation uses the tier names Start, Build and Scale and the numbers above, so do not rely on the older tables.
Common errors and what to do#
| Status | Error type | What it means | Fix |
|---|---|---|---|
| 400 | invalid_request_error | Bad request format or an unsupported setting | Read the message. See the table of old habits above |
| 401 | authentication_error | Key is wrong, revoked or expired | Create a new key |
| 402 | billing_error | Problem with billing or payment | Check the Billing page |
| 403 | permission_error | Key lacks permission for that resource | Check workspace and role |
| 404 | not_found_error | Resource or endpoint not found | Check the URL and IDs |
| 413 | request_too_large | Request over the size limit (32 MB on Messages) | Send less data |
| 429 | rate_limit_error | Rate limit or monthly spend cap hit | Honor retry-after, slow down |
| 500 | api_error | Problem inside Anthropic | Retry with backoff |
| 529 | overloaded_error | API busy across all users | Retry later |
Two traps are worth remembering. A spend-cap 429 has no retry-after header and fails until the next month begins, so retrying does nothing. Its body includes error_code: enforced_spend_limit_reached, which is how you tell it apart from an ordinary rate limit. And if you set your own spend limit lower than the tier cap, hitting it returns a 400, not a 429.
The official SDK already retries connection errors, rate limits and 5xx errors twice by default, with exponential backoff, and it honors retry-after. You can change that with max_retries. A short, typed error handler is usually all you need on top:
import anthropic
client = anthropic.Anthropic(max_retries=3)
try:
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=1000,
messages=[{"role": "user", "content": "Summarize HTTP caching in two lines."}],
)
print(message.usage.input_tokens, message.usage.output_tokens)
except anthropic.RateLimitError as err:
print("Rate limited or spend cap reached:", err.status_code)
except anthropic.APIStatusError as err:
print("API error:", err.status_code, err.message)
except anthropic.APIConnectionError:
print("Network problem. Try again.")Catch the specific classes first, as above, so a 400 (your bug) is not treated like a 429 (slow down).
Streaming and structured JSON#
Streaming shows text as it is written, so long answers feel fast and requests do not time out. Anthropic's example is short:
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
model="claude-opus-5-5",
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)If you set a very large max_tokens (Anthropic's errors page gives 128,000 as an example), use streaming. If you do not need to show the text as it arrives, call stream.get_final_message() and you get the complete message object.
Structured outputs make Claude return JSON that matches a schema, which is far safer than asking nicely and parsing text. With Pydantic in Python:
from pydantic import BaseModel
from anthropic import Anthropic
class ContactInfo(BaseModel):
name: str
email: str
plan_interest: str
demo_requested: bool
client = Anthropic()
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Extract the key information from this email: John Smith ([email protected]) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",
}],
output_format=ContactInfo,
)
print(response.parsed_output)Limits to know from Anthropic's page: objects must set additionalProperties to false, some schema features such as recursive schemas and minLength are unsupported, and a refusal can still break the schema. For tools and API design in general, our guide to API design principles explains why clear schemas matter.
Keep your API key safe#
An API key is a password that spends money. Anthropic's authentication page and the tutorials agree on the basics:
- Never put the key in your code or in a public repository. Use the
ANTHROPIC_API_KEYenvironment variable or a secrets manager. - Use short expirations while testing. A 7-day or 30-day key limits the damage if it leaks. Anthropic emails the key's creator before an expiry, but not for keys with very short lives.
- Give each app its own key, scoped to one workspace, so you can see who spent what and shut one off without breaking the rest. One tutorial also warns against sharing a single key between development and production.
- Use a service account key for shared or automated work, so it does not depend on one person's account.
- If a key leaks, disable it at once. Disable is reversible; delete is permanent.
- Do not ship a key inside a browser or mobile app. Call Claude from your own server. For iOS and macOS apps, Anthropic offers App Attest, which issues short-lived tokens instead.
- In production on a cloud platform, Anthropic recommends Workload Identity Federation, which swaps a long-lived key for short-lived tokens.
What the tutorials get wrong, and right#
We read seven third-party guides next to Anthropic's own pages. This is not a knock on their authors: model pages move fast, and a guide ages in months. It does show why you should check the date and the model ID before you copy anything.
| Guide | What we noticed |
|---|---|
| KDnuggets (July 2026) | Clear Python walkthrough. Its advice on system prompts, max_tokens and stateless history matches Anthropic's docs |
| Zapier | Useful on keys and prepaid billing. Its sample uses claude-sonnet-5 while its price table lists Sonnet 5.5 |
| Reintech (January 2026) | Uses claude-3-5-sonnet-20241022 and prices "as of 2024" |
| DEV: rate limits guide | Good 429 advice (honor retry-after, use jitter). Its Tier 1 to 4 table does not match the Start, Build and Scale tiers in the current docs |
| DataCamp cheat sheet (May 2026) | Uses 4.6-generation IDs. Its example puts the system prompt inside the messages list, while the API takes it as a top-level system field |
| PublicAPIs.io guide | Uses claude-sonnet-4-20250514 labeled as the latest, quotes older per-model prices, and calls prompt caching an "enterprise feature" with "up to 50%" savings. Anthropic's pricing page shows caching reads at 0.1x or less of the input price for every model |
| MetaCTO | Prices match Anthropic's page, but its code sample uses claude-sonnet-4-6 and its FAQ describes a "thinking budget" that newer models reject |
Our rule of thumb: trust the model IDs, prices and limits on Anthropic's pages, and use the guides for ideas and examples. For more on spotting stale advice, see our post on outdated API tutorials. If you are comparing providers, our OpenAI API guide shows the same kind of walkthrough for GPT models.
Production checklist#
- Key stored in an environment variable or secrets manager, never in Git.
- One key per app, with a sensible expiration.
- Model ID copied from the models page, not from a blog post.
-
max_tokensset high enough, andstop_reasonchecked formax_tokens. -
usagelogged on every call, including cache fields. - A monthly spend limit set on the Billing page, below your tier's cap.
- Typed error handling: 400 is a bug, 429 means slow down, 529 means retry later.
- Prompt caching on any prompt that repeats and is 512 tokens or more.
- Batch API for work that can wait.
- A test set of real examples, run on a cheaper model first.
Key takeaways#
- Output tokens cost 5x input tokens, and hidden thinking is billed as output, so read
usageinstead of guessing. - The same traffic can cost $13.50 or $1,350 a month depending on the model you choose.
- Prompt caching and the Batch API are the two big levers, and they can stack.
- Limits come from your tier (Start, Build, Scale) and are checked in requests and tokens per minute. A spend-cap 429 cannot be retried away.
- Many older settings, such as prefill,
budget_tokensand forced tool choice, now return a 400 on current models. - Keep keys out of code, scope them per app and give them an expiry.
Sources we read#
We read these 19 sources on 20 October 2026. Prices and limits change, so check the official pages before you budget.
Anthropic documentation (12): Pricing, Models overview, Rate limits, Get started, Errors, Prompt caching, Batch processing, Streaming, Structured outputs, Token counting, Authentication, Thinking.
Third-party guides (7): KDnuggets, Zapier, Reintech, DEV Community rate limits guide, DataCamp, PublicAPIs.io, MetaCTO.
We also checked Google Trends (United States, past 90 days, 20 October 2026) to choose this topic: "claude api" averaged about 65 on Google's 0 to 100 scale, well above "free ai api" (about 15) and "openai api key" (about 8).