← Blog

Claude API SDK for Python Quickstart

2026-10-31 · 5 min read · SubToAPI Team

If you're searching for "claude api sdk for python quickstart," you want the shortest path from zero to a working Claude API call in Python: install the right package, get a key, send a message, and get a response back. This guide covers exactly that, plus streaming, tool use, and error handling so you're not back here in an hour debugging a 429.

The official Python SDK is the anthropic package on PyPI. It wraps the Messages API, handles retries and streaming, and gives you typed request/response objects instead of raw JSON. Below is everything you need to go from pip install to a production-ready script.

Installing the SDK

pip install anthropic

If you're using a virtual environment (you should be), activate it first:

python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install anthropic

That's the entire install step. No build tools, no native dependencies.

Getting an API Key

You need a key before you can call anything. There are two common paths:

  1. Anthropic Console — create an account, set up billing, generate a key. Works, but approval and billing setup can take a bit of back-and-forth if you're adding a team or need usage tracking across projects.
  2. A hosted gateway like SubToAPI — if you already have Claude access and just want an instant HTTPS API key with usage metadata and team seats, you can sign up at /signup and get a sub_live_... key in minutes. It's a drop-in HTTPS endpoint, not a Python library, so you'd call it with requests or httpx instead of the anthropic SDK — more on that below.

For this quickstart, we'll use the official SDK against the standard Anthropic endpoint, since that's what "Python SDK" implies.

Set your key as an environment variable so it never ends up hardcoded in your repo:

export ANTHROPIC_API_KEY="your-key-here"

Your First Request

Here's the minimal script to send a message and print the response:

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from env

message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain what a quickstart guide is, in one sentence."}
    ],
)

print(message.content[0].text)

Run it:

python quickstart.py

A few things worth noting:

Multi-Turn Conversations

The SDK doesn't maintain conversation state for you — you pass the full message history on every call:

messages = [
    {"role": "user", "content": "What's the capital of Portugal?"},
    {"role": "assistant", "content": "Lisbon."},
    {"role": "user", "content": "And its population?"},
]

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=512,
    messages=messages,
)
print(response.content[0].text)

You're responsible for appending each turn to the list and trimming it as it grows, since the model has a context window limit.

Streaming Responses

For chat UIs or long completions, streaming avoids making users stare at a blank screen:

with client.messages.stream(
    model="claude-3-5-sonnet-20241022",
    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 stream.text_stream iterator yields text chunks as they arrive — no manual SSE parsing required.

Using Tools (Function Calling)

Claude can call functions you define, which is useful for anything involving live data, calculations, or structured actions:

tools = [
    {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    }
]

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=512,
    tools=tools,
    messages=[{"role": "user", "content": "What's the weather in Lisbon?"}],
)

for block in response.content:
    if block.type == "tool_use":
        print("Tool call:", block.name, block.input)

Claude returns a tool_use content block with the function name and arguments; you run the actual logic and send the result back in a follow-up message with tool_result.

Handling Errors

Wrap calls in try/except for anything hitting production:

from anthropic import APIStatusError, RateLimitError

try:
    response = client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=256,
        messages=[{"role": "user", "content": "Hello"}],
    )
except RateLimitError:
    print("Rate limited — back off and retry.")
except APIStatusError as e:
    print(f"API error: {e.status_code} — {e.message}")

If You Need Team Keys Instead

The official SDK is great for a single app talking to a single key. If you're building something with multiple services, teammates, or client apps that all need Claude access with per-key usage tracking, raw API keys get messy fast. That's the gap SubToAPI fills: issue separate sub_live_... keys per app or teammate, see usage per key in a dashboard, and keep billing on one invoice across /pricing plans (Solo, Team, Scale).

Since SubToAPI exposes an HTTP endpoint rather than its own Python package, you'd call it the same way you'd call any REST API:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 256,
    "messages": [{"role": "user", "content": "Hello"}]
  }'

In Python, that's just requests.post() with the same JSON body. Full request/response shapes are in /docs/messages, streaming setup is in /docs/streaming, and tool definitions follow the same schema covered above — see /docs/tools. The general setup flow is in /docs/quickstart.

Questions

Do I need the official anthropic package, or can I just use requests? Either works. The SDK saves you from writing retry logic, streaming parsers, and type validation yourself. requests is fine if you want full control or are calling a gateway endpoint directly.

What Python version does the SDK require? Python 3.8 or newer. It has minimal dependencies (mainly httpx under the hood) and installs cleanly with pip.

Can I use the same Python code against a hosted gateway like SubToAPI? Yes, as long as the gateway exposes a compatible Messages API shape — point requests or httpx at the gateway's endpoint with its API key instead of calling anthropic.Anthropic() directly.

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 →