How to Use the Claude API: SDK Setup, Pricing, Long Context and Prompt Caching
Published October 21, 2026 · Last updated October 21, 2026
Some links on this page are affiliate links. If you buy through them, we may earn a commission at no extra cost to you. This never influences our rankings or opinions.
Claude is the go-to API for long documents, careful writing and agentic coding. The Anthropic API is clean and well documented; this guide covers setup, the exact code you need, and the cost mechanics that matter (caching especially).
Step 1: Get an API key
- Go to https://console.anthropic.com and create an account (separate from claude.ai).
- Under Billing, add a payment method and buy initial credits (API is credit-based).
- API Keys → Create Key, name it, copy it once.
Environment variable (do this before writing code):
export ANTHROPIC_API_KEY="sk-ant-..."
echo 'export ANTHROPIC_API_KEY="sk-ant-..."' >> ~/.zshrc
Windows PowerShell:
[Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "sk-ant-...", "User")
Step 2: First request in Python
pip install anthropic
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
resp = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system="You are a precise technical assistant. Be concise.",
messages=[
{"role": "user", "content": "Explain prompt caching in one paragraph."}
],
)
print(resp.content[0].text)
print("in:", resp.usage.input_tokens, "out:", resp.usage.output_tokens)
Notes on the shape (it differs from OpenAI):
systemis a top-level parameter, not a message role.- The response object wraps content blocks; text lives in
content[0].text. max_tokensis required — the API rejects requests without it.
Step 3: First request with curl (works anywhere)
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"max_tokens": 512,
"messages": [{"role": "user", "content": "Hello, Claude"}]
}'

Step 4: Pick the right model
Current line-up (API IDs, October 2026):
| Model | API ID | Input $/1M | Output $/1M | Use it for |
|---|---|---|---|---|
| Claude Opus 5.5 | claude-opus-5-5 | $4 | $20 | hard coding, agents, complex analysis |
| Claude Sonnet 5.5 | claude-sonnet-5-5 | $2 | $10 | default all-rounder |
| Claude Haiku 5.5 | claude-haiku-5-5 | $0.10 | $0.50 | high volume, classification, routing |
Start with Sonnet 5.5; only reach for Opus when quality actually matters, and drop to Haiku for anything mechanical.
Step 5: Long documents (the reason people choose Claude)
All current models take 1M-token contexts. Practical tips:
resp = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=4096,
messages=[{
"role": "user",
"content": [
{"type": "document", "source": {
"type": "base64",
"media_type": "application/pdf",
"data": pdf_b64,
}},
{"type": "text", "text": "Summarize the key obligations."},
],
}],
)
- Send whole documents instead of chunking — Claude is trained for full-context reasoning.
- Put instructions after the document for better grounding.
- For 200K+ token prompts, double-check pricing tiers on the pricing page.
Step 6: Prompt caching (the biggest cost lever)
Caching turns repeated prompt prefixes into 10x-cheaper reads. Any stable prefix qualifies: system prompts, retrieved docs, tool schemas.
resp = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system=[{
"type": "text",
"text": LARGE_SYSTEM_PROMPT, # stays identical across calls
"cache_control": {"type": "ephemeral"},
}],
messages=[{"role": "user", "content": user_question}],
)
print(resp.usage) # shows cache_read_input_tokens when the cache hit
Cache rules in short: the prefix must be byte-identical, entries last ~5 minutes (refreshed on use), and cache writes cost 25% extra once. If your app reuses the same system prompt or retrieval context, this typically cuts input costs 50-90%.
Step 7: Handling errors properly
import time
from anthropic import RateLimitError, APIConnectionError
def ask(prompt: str, retries: int = 3):
for attempt in range(retries):
try:
return client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
)
except RateLimitError:
time.sleep(2 ** attempt * 5)
except APIConnectionError:
time.sleep(2 ** attempt * 10)
raise RuntimeError("Claude API unavailable after retries")
The most common surprises: invalid_request_error for missing max_tokens (required,
unlike OpenAI), and 429s during capacity crunches — backoff is honored, retries get through.
Where Claude beats and loses
- Wins: long-context document work, nuanced writing, coding agents (most top coding tools default to Claude models — see OpenCode), careful instruction following.
- Loses: raw price on simple tasks (DeepSeek and Gemini Flash are far cheaper), and strict rate limits on new accounts.
Next steps
- Model comparison to sanity-check prices against OpenAI and Gemini.
- Run Claude-family models locally? Not possible (closed weights) — but local alternatives exist via Ollama for cheaper tasks.
- Build agents with the official SDKs; the Claude Code CLI shows the pattern in practice.