← Blog

Claude API Python SDK Quickstart Tutorial

2026-11-21 · 5 min read · SubToAPI Team

What this tutorial covers

If you want to call Claude from Python, you need three things: the anthropic package installed, a valid API key set as an environment variable, and a basic understanding of the Messages API shape (model, messages, max_tokens). This tutorial walks through all three, then adds streaming and a simple multi-turn conversation loop so you have a working starting point rather than a toy snippet.

By the end you'll have a script that sends a prompt to Claude, prints the response, and streams tokens as they arrive — the same pattern you'd use in a real application, whether you're hitting Anthropic directly or routing through a proxy like SubToAPI that wraps your Claude access in a standard HTTPS API.

Step 1: Install the SDK

pip install anthropic

This installs the official Python client, which handles request signing, retries, and streaming for you. Check your version matches the latest release if you hit unexpected errors — Anthropic updates the SDK fairly often as new models and parameters ship.

Step 2: Set your API key

The SDK reads your key from the ANTHROPIC_API_KEY environment variable by default:

export ANTHROPIC_API_KEY="sk-ant-..."

On Windows PowerShell:

$env:ANTHROPIC_API_KEY="sk-ant-..."

Never hardcode the key in your script or commit it to version control. If you're running this in a team or production context, see our guide on Anthropic API key best practices for rotation and scoping advice.

Step 3: Your first API call

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY automatically

message = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain what a quickstart tutorial should include."}
    ],
)

print(message.content[0].text)

A few things worth knowing about this call:

The response object includes content (a list of content blocks, usually text), usage (input/output token counts), and stop_reason (why generation ended). Checking stop_reason matters in production — max_tokens means you got truncated, end_turn means Claude finished naturally.

Step 4: Multi-turn conversations

Claude doesn't maintain state between calls — you resend the full conversation history each time:

history = [
    {"role": "user", "content": "What's a good name for a note-taking app?"}
]

reply = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=512,
    messages=history,
)

history.append({"role": "assistant", "content": reply.content[0].text})
history.append({"role": "user", "content": "Make it sound more playful."})

reply2 = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=512,
    messages=history,
)

print(reply2.content[0].text)

This pattern — append, call, append, call — is the core of every chatbot built on Claude. For anything beyond a demo script, you'll want to persist this history to a database rather than an in-memory list, but the request shape stays identical.

Step 5: Streaming responses

For anything user-facing, streaming avoids making people stare at a blank screen while a long response generates:

with client.messages.stream(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a short poem about debugging."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

The SDK exposes a text_stream iterator that yields chunks as they arrive, which you can pipe directly into a terminal, a WebSocket, or a server-sent events endpoint for a frontend.

Step 6: System prompts and temperature

Two parameters you'll use constantly:

message = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    system="You are a terse technical writer. No filler sentences.",
    temperature=0.3,
    messages=[{"role": "user", "content": "Summarize what REST means."}],
)

An alternative: a drop-in HTTPS endpoint

If you're building a product on top of this and need application-specific API keys, per-team usage tracking, or a dashboard for billing without managing Anthropic's console yourself, SubToAPI puts the same Messages API behind your own sub_live_... keys. The request shape is nearly identical to what you've just written:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-opus-4-20250514",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello, Claude"}]
  }'

This is useful when you're shipping a product to customers and don't want to expose your underlying Anthropic credentials or manage separate billing per client. Issuing a scoped key per customer, tracking their usage, and rotating keys without touching your core integration is covered in the quickstart docs and the Messages API reference. Streaming and tool use work the same way as above — see streaming and tools for the specifics. Plans start at the pricing page, with a free trial available from signup.

Putting it together

A minimal but production-shaped script combines error handling, streaming, and a system prompt:

import anthropic

client = anthropic.Anthropic()

try:
    with client.messages.stream(
        model="claude-opus-4-20250514",
        max_tokens=1024,
        system="Answer concisely.",
        messages=[{"role": "user", "content": "What is Python's GIL?"}],
    ) as stream:
        for text in stream.text_stream:
            print(text, end="", flush=True)
except anthropic.APIError as e:
    print(f"API error: {e}")

That's the full loop: install, authenticate, call, stream, handle failures. Everything else — multi-agent orchestration, tool use, vision input — builds on this same foundation.

questions

Do I need an Anthropic account to use the Python SDK? Yes, you need an API key from Anthropic's console (or from a provider like SubToAPI that issues keys backed by Claude access) before the SDK can authenticate requests.

Why is my response getting cut off? Check stop_reason on the response object. If it's max_tokens, increase the max_tokens parameter in your request — the model stopped because it hit the length cap, not because it finished.

Can I use the Python SDK with async code? Yes, anthropic ships an AsyncAnthropic client with the same method signatures, so you can await client.messages.create(...) inside async functions without changing your request structure.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →