Claude API SDK for Python Quickstart
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:
- 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.
- 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 withrequestsorhttpxinstead of theanthropicSDK — 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:
max_tokensis required — there's no default, so forgetting it throws an error.message.contentis a list of content blocks, not a single string. For plain text responses, grab.textoff the first block.- The client automatically retries on transient 5xx errors and rate-limit responses with exponential backoff.
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.