Skip to content
Easy AI How-To

AdvancedClaudeBuilding

Call the Claude API in Python and cut costs with prompt caching

This guide is for developers. You will make a real Claude API call from Python, then add prompt caching, which lowers cost and latency when many requests share the same long instructions or documents. Each technical term is explained when it first appears.

Time
About 30 minutes
Checked
Tools
Claude Console, Claude API docs

If a button name on the screen does not match this guide, follow the action. These products rename buttons often. This is an advanced guide: it uses code, and each technical term is explained the first time it appears. Model names and prices change, so check the linked docs before you ship.

Steps

  1. Create an API key

    An API key is a secret password your code uses to call Claude. In the Claude Console, open API keys, create one, and copy it. Store it in an environment variable (a setting your terminal passes to programs), never in your code:

    export ANTHROPIC_API_KEY="your-key-here"
    
  2. Install the SDK

    An SDK is a library that wraps the raw web requests. Make a project folder with a virtual environment (an isolated set of Python packages):

    mkdir claude-demo && cd claude-demo
    python3 -m venv .venv && source .venv/bin/activate
    pip install anthropic
    
  3. Make your first call

    Save this as first.py and run python first.py. The model is which Claude you use; max_tokens caps the reply length (a token is roughly three-quarters of a word).

    import anthropic
    
    client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
    
    message = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=1000,
        messages=[{"role": "user", "content": "Give me 3 names for a hiking app."}],
    )
    for block in message.content:
        if block.type == "text":
            print(block.text)
    print(message.usage)
    
  4. Understand what caching saves

    Prompt caching stores the start of a prompt (the "prefix") on Anthropic's side for a few minutes. If the next request starts with exactly the same text, Claude reads it from the cache: cache reads are billed at a small fraction of normal input price, and responses start faster. Writing to the cache costs a bit more than normal input. It pays off when a long, identical prefix is reused several times.

  5. Mark the reusable part with cache_control

    Put the stable content (instructions, a long document) first, and mark the end of it with cache_control. Put the part that changes (the user's question) after it.

    import anthropic
    
    client = anthropic.Anthropic()
    handbook = open("handbook.txt").read()  # long, unchanging text
    
    def ask(question: str):
        return client.messages.create(
            model="claude-sonnet-5-5",
            max_tokens=800,
            system=[
                {"type": "text", "text": "Answer only from the handbook. Quote the section."},
                {
                    "type": "text",
                    "text": handbook,
                    "cache_control": {"type": "ephemeral"},
                },
            ],
            messages=[{"role": "user", "content": question}],
        )
    
    for q in ["How many vacation days do I get?", "What is the expense limit?"]:
        r = ask(q)
        print(r.usage.cache_creation_input_tokens, r.usage.cache_read_input_tokens)
    
  6. Confirm the cache is hit

    The first call should show tokens in cache_creation_input_tokens (written to cache). The second, sent within about 5 minutes, should show them in cache_read_input_tokens. If both are 0, the prefix is below the model's minimum cacheable length, or something before the breakpoint changed between calls.

Tips

  • For multi-turn chats, you can add a single top-level cache_control={"type": "ephemeral"} to the request and let the API move the cache point forward automatically.

  • The default cache lasts 5 minutes and refreshes each time it's used. A 1-hour option exists at a higher write price: {"type": "ephemeral", "ttl": "1h"}.

  • Anything that changes before the breakpoint (a timestamp, a different tool list) breaks the cache. Keep variable content after it.

Common questions

Which model should I start with?

Anthropic's models page lists current IDs and prices. At the time of checking, claude-sonnet-5-5 balances speed and quality, claude-haiku-5-5 is cheapest and fastest, and claude-opus-5-5 is the default recommendation for hard work. Model names change, so check the page.

Does my Claude Pro subscription cover API use?

No. The API is billed separately in the Claude Console.

Is caching the same as Claude remembering things?

No. It only saves cost and time on identical prompt text. You still send the full prompt every time.

Occasional notes

Hear when a new guide is up

A short note when a guide is added. No account, and no emails until this form is connected to a real list.

Placeholder. This form is not connected to an email service. Nothing you type is saved or sent.