Claude API SDK for Python Developers: Setup Guide
What "Claude API SDK for Python" Actually Means
If you're searching for this, you're almost certainly trying to do one of two things: call Claude from a Python script using Anthropic's official anthropic package, or figure out how to get programmatic access to Claude in the first place without writing raw HTTP requests by hand. This guide covers both — the SDK itself, and what to do once you need more than a single script (teams, usage tracking, multiple keys).
The short answer: Anthropic publishes an official Python SDK (pip install anthropic) that wraps the Messages API with typed request/response objects, built-in retries, and streaming support. It's the standard way Python developers integrate Claude. Below is everything you need to get from zero to a working integration, plus the gaps you'll hit once you're shipping to production.
Installing and Authenticating
pip install anthropic
The SDK reads your API key from an environment variable by default:
export ANTHROPIC_API_KEY="sk-ant-..."
import anthropic
client = anthropic.Anthropic() # picks up ANTHROPIC_API_KEY automatically
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Explain closures in Python."}]
)
print(message.content[0].text)
That's the entire core pattern: instantiate a client, call messages.create, read .content. Everything else in the SDK is variations on this.
Sending Structured Conversations
Claude's API is stateless — you send the full conversation history on every call. The SDK's messages list is just a list of dicts with role and content:
history = [
{"role": "user", "content": "What's a list comprehension?"},
{"role": "assistant", "content": "It's a concise way to build lists..."},
{"role": "user", "content": "Show me one that filters even numbers."}
]
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=512,
messages=history
)
A common mistake for developers coming from other APIs is forgetting that system prompts are a separate top-level parameter, not a message in the list:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=512,
system="You are a terse Python tutor. Answer in code only.",
messages=history
)
Streaming Responses
For chat UIs or anything latency-sensitive, streaming avoids waiting for the full response:
with client.messages.stream(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about recursion."}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
The SDK handles the server-sent events parsing for you — you just iterate tokens as they arrive.
Tool Use (Function Calling)
Claude can call functions you define, which the SDK represents as a tools parameter with JSON Schema definitions:
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-sonnet-4-5",
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(block.name, block.input)
You then run get_weather(city="Lisbon") yourself, send the result back as a tool_result message, and Claude continues the conversation with that data. This is the pattern behind most agent frameworks — the SDK just gives you the raw building blocks.
Handling Errors and Rate Limits
The SDK raises typed exceptions you can catch specifically:
from anthropic import APIStatusError, RateLimitError
try:
client.messages.create(
model="claude-sonnet-4-5",
max_tokens=512,
messages=[{"role": "user", "content": "Hello"}]
)
except RateLimitError:
print("Back off and retry")
except APIStatusError as e:
print(f"API error: {e.status_code} - {e.message}")
The SDK also retries transient failures (connection errors, 5xx responses) automatically a few times before raising — you can tune this with the max_retries parameter on the client constructor.
When a Single Key and Script Isn't Enough
The official SDK is excellent for a single developer prototyping or building one application. It gets harder to manage once you have multiple apps, multiple team members, or a need to see per-project usage without digging through logs — Anthropic's console gives you one account-level key, not scoped per-application keys with individual tracking.
This is the gap SubToAPI fills. It sits in front of your existing Claude access and issues separate sub_live_... API keys per application or team member, with usage metadata and streaming exposed through a standard HTTPS endpoint — the same messages.create shape you're already using in Python, just pointed at https://api.subtoapi.app/v1/messages:
import requests
response = requests.post(
"https://api.subtoapi.app/v1/messages",
headers={"Authorization": "Bearer sub_live_..."},
json={
"model": "claude-sonnet-4-5",
"max_tokens": 512,
"messages": [{"role": "user", "content": "Summarize this changelog."}]
}
)
If you're already comfortable with the Anthropic Python SDK's request format, switching the base URL and key is the only change required — see the full request/response reference in the docs and the streaming guide if your Python app needs token-by-token output.
Choosing Between the Raw SDK and a Managed Layer
For a solo script or weekend project, pip install anthropic plus a single API key is all you need — it's free to start and has zero overhead. Reach for something like SubToAPI when you need:
- Separate keys per application or environment (dev, staging, prod) without separate Anthropic accounts
- Per-key usage visibility for billing clients or internal cost allocation
- Team seats so multiple developers share one underlying Claude access without sharing a raw key
- A dashboard instead of parsing logs to answer "which app made this call"
Plans start at €9/month for solo developers, with team and scale tiers at €19 and €49 per seat — see pricing for details, or start with the quickstart and a free trial to see if it fits your workflow.
Tool Use Beyond the Basics
Once you're past "call Claude and print the answer," most Python integrations end up combining tool use with streaming — streaming the text response while handling tool calls mid-stream. The official SDK supports this via event handlers on the stream context manager (on_tool_use, etc.), and the pattern is identical whether you're hitting Anthropic directly or through a proxy like SubToAPI's tools documentation, since both follow the same Messages API shape.
Questions
Does Anthropic have an official Python SDK, or do I need a third-party library? Anthropic maintains an official anthropic PyPI package with typed clients, streaming, and retry logic. There's no need for a third-party wrapper for basic usage.
Can I use the same Python code with SubToAPI instead of calling Anthropic directly? Yes. SubToAPI exposes the same Messages API request/response format, so you only need to change the base URL and API key in your existing Python client.
Is the Python SDK free to use? The SDK itself is free and open source; you pay for the underlying Claude API usage through your Anthropic account or a provider like SubToAPI that manages that access for you.