Skip to content
APIHiver

Claude API Guide: Setup, Pricing & Rate Limits (2026)

Set up the Claude API, pick a model and estimate real costs. We checked Anthropic's docs and 19 sources on pricing, limits, errors and caching.

19 min readBy Mivaan Sanghani
In this post

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.

A developer's desk in soft morning light with an open laptop, a notebook with pencil notes and a cup of coffee, representing setting up the Claude API

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-5 that 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#

  1. Create an account in the Claude Console (platform.claude.com).
  2. Go to the API keys page and click Create key.
  3. 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.
  4. 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 anthropic
import 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 whose type is text, as the example does. Newer models can also return thinking blocks, so never assume the first block is the answer.
  • stop_reason: end_turn means Claude finished. max_tokens means 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.
  • id and the request-id header: 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.1Claude Opus 5.5Claude Sonnet 5.5Claude Haiku 5.5
Model IDclaude-fable-5-1claude-opus-5-5claude-sonnet-5-5claude-haiku-5-5
Anthropic's descriptionDemanding reasoning, long agent workLong agentic coding and knowledge workBest mix of speed and intelligenceHigh-volume, fast jobs
Input price per million tokens$10$4$2$0.10
Output price per million tokens$50$20$10$0.50
SpeedSlowerModerateFastFastest
Default efforthighmediumhighmedium
RetirementNot before 1 Sep 2027Not before 22 Sep 2027Not before 28 Sep 2027Not 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 habitWhat happens nowWhat to do
Pre-fill the start of Claude's answer (a final assistant message)400 on Claude 4.6 and laterUse structured outputs or tell Claude the format in the prompt
thinking: {"type": "enabled", "budget_tokens": 5000}400 on Claude 4.7 and laterOmit 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 onLower the effort setting instead
Forcing a tool with tool_choice set to any or a named tool400 on Fable 5.1, Opus 5.5 and Sonnet 5.5Use auto and say in the prompt which tool to use
Copying an old model ID such as claude-3-5-sonnet-20241022Old IDs belong to retired modelsTake 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):

ModelCost per request1,000 requests per dayOver 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.

A hand-held calculator, a notebook with pencil figures and a cup of coffee on a kitchen table, representing estimating Claude API costs before building

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 tierMonthly 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:

TierModelRPMITPMOTPM
StartOpus 5.5, Sonnet 5.5, Haiku 5.51,0002,000,000400,000
StartFable 5.x1,000500,000100,000
BuildOpus 5.5, Sonnet 5.5, Haiku 5.55,0005,000,0001,000,000
BuildFable 5.x2,0001,500,000300,000
ScaleOpus 5.5, Sonnet 5.5, Haiku 5.510,00010,000,0002,000,000
ScaleFable 5.x4,0004,000,000800,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_tokens is free of limit math. OTPM counts only the tokens actually generated, so a high max_tokens does 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#

StatusError typeWhat it meansFix
400invalid_request_errorBad request format or an unsupported settingRead the message. See the table of old habits above
401authentication_errorKey is wrong, revoked or expiredCreate a new key
402billing_errorProblem with billing or paymentCheck the Billing page
403permission_errorKey lacks permission for that resourceCheck workspace and role
404not_found_errorResource or endpoint not foundCheck the URL and IDs
413request_too_largeRequest over the size limit (32 MB on Messages)Send less data
429rate_limit_errorRate limit or monthly spend cap hitHonor retry-after, slow down
500api_errorProblem inside AnthropicRetry with backoff
529overloaded_errorAPI busy across all usersRetry 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:

A small bundle of brass keys hanging from a hook on a wooden wall beside a closed door, representing keeping an API key safe
  • Never put the key in your code or in a public repository. Use the ANTHROPIC_API_KEY environment 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.

GuideWhat we noticed
KDnuggets (July 2026)Clear Python walkthrough. Its advice on system prompts, max_tokens and stateless history matches Anthropic's docs
ZapierUseful 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 guideGood 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 guideUses 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
MetaCTOPrices 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_tokens set high enough, and stop_reason checked for max_tokens.
  • usage logged 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 usage instead 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_tokens and 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).

Try APIs on the APIHiver marketplace

Discover free and paid APIs for travel, finance, AI, weather, maps and more. Test each endpoint in your browser and use one key for all of them.

Share this post

Frequently asked questions

How do I get a Claude API key?
Create an account in the Claude Console, open the API keys page and click Create key. Name the key, pick an expiration, and copy it straight away, because it is shown only once. Then save it as the ANTHROPIC_API_KEY environment variable. Anthropic's official SDKs read that variable automatically, so you do not have to paste the key into your code.
Is the Claude API free?
Not in the way most people hope. The API is billed per token, and Zapier's guide says you buy prepaid credits with a $5 minimum. We could not confirm a permanent free tier on Anthropic's own pages, so treat any tutorial that promises free credits with caution and check the Console before you build. Cheap is realistic: Claude Haiku 5.5 costs $0.10 per million input tokens.
Which Claude model should I use?
Anthropic's models page says to start with Claude Opus 5.5 for most workloads. Use Claude Fable 5.1 for the hardest reasoning and long agent tasks. Use Claude Sonnet 5.5 when you want a faster, cheaper everyday model, and Claude Haiku 5.5 for high-volume jobs such as classification and extraction. Run a small test on your own prompts before you commit.
How much does the Claude API cost per request?
It depends on tokens, not requests. A request with 2,000 input tokens and 500 output tokens costs about $0.018 on Claude Opus 5.5, $0.009 on Claude Sonnet 5.5 and $0.00045 on Claude Haiku 5.5, using Anthropic's October 2026 prices. Thinking tokens are billed as output tokens, so real bills can run higher than this simple sum.
What are the Claude API rate limits?
Limits are set per organization by usage tier (Start, Build or Scale) and are measured in requests, input tokens and output tokens per minute. For example, Claude Sonnet 5.5 allows 1,000 requests per minute on the Start tier and 5,000 on Build. New organizations may begin in an Evaluation tier with lower limits. Your exact numbers are on the Rate limits page of the Console.
What does a 429 error mean from the Claude API?
You hit a rate limit, or your tier's monthly spend cap. If the response has a retry-after header, wait that many seconds. A spend-cap 429 has no retry-after header and keeps failing until access resumes at the start of the next month, so retrying does not help. Anthropic's SDKs already retry transient errors twice by default.
Does a Claude subscription include API access?
We could not open Anthropic's support article on this, so we do not claim an answer. What we did confirm is that the API runs through a separate Claude Console account with its own keys and billing. Check Anthropic's current support page before you assume one covers the other.
AI & Machine Learning

Best Image Generation API for Production Apps (2026)

Which image generation API is best for a live app? We compare OpenAI, Google Gemini, FLUX and Stability on cost, limits, uptime risk and model shutdowns.

11 min read