How to Use the Claude API: SDK Setup, Pricing, Long Context and Prompt Caching

Published October 21, 2026 · Last updated October 21, 2026

How to Use the Claude API: SDK Setup, Pricing, Long Context and Prompt Caching
Photo by Alejandro Escamilla (Unsplash)
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

  1. Go to https://console.anthropic.com and create an account (separate from claude.ai).
  2. Under Billing, add a payment method and buy initial credits (API is credit-based).
  3. 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):

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"}]
  }'

Screenshot: curl request to the Messages API with the JSON response

Step 4: Pick the right model

Current line-up (API IDs, October 2026):

ModelAPI IDInput $/1MOutput $/1MUse it for
Claude Opus 5.5claude-opus-5-5$4$20hard coding, agents, complex analysis
Claude Sonnet 5.5claude-sonnet-5-5$2$10default all-rounder
Claude Haiku 5.5claude-haiku-5-5$0.10$0.50high 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."},
        ],
    }],
)

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

Next steps