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

> Get an API key, make your first Claude Messages API call in Python, then add prompt caching so repeated long prompts cost less and run faster.

Level: Advanced
Tool: Claude
Category: Building
Time: About 30 minutes
Checked: 2026-10-15
Tools: [Claude Console](https://console.anthropic.com), [Claude API docs](https://docs.anthropic.com/en/docs/get-started)
HTML page: https://easyaihowtos.com/guides/call-the-claude-api-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.

## What you need

- Python 3.9 or newer and a terminal
- A Claude Console account with billing set up (API use is pay-as-you-go, separate from a claude.ai subscription)
- A long document or instructions you send with many requests (for the caching part)

## 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:
```bash
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):
```bash
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).
```python
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.
```python
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.

## FAQ

### 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.

---

This guide is from Easy AI How-To (https://easyaihowtos.com). It is independent of the tools named above. Screens and free-plan limits change, so check the date before you rely on a button name.
