Claude API Python Client Library Setup Guide
Setting up the Claude API Python client takes about five minutes once you know the right sequence: install the anthropic package, get an API key, initialize the client, and send your first message. This guide walks through each step, including streaming, error handling, and what to do if you're building on top of an existing Claude subscription rather than a direct Anthropic API key.
If you already have Python 3.8+ installed, the whole setup is three commands and ten lines of code. The rest of this article covers the details that trip people up: environment variable naming, timeout configuration, and how to structure requests so they don't break when Anthropic ships API changes.
Installing the client library
Anthropic maintains an official Python SDK. Install it with pip:
pip install anthropic
If you're working inside a virtual environment (recommended for any real project), activate it first:
python -m venv venv
source venv/bin/activate # on Windows: venv\Scripts\activate
pip install anthropic
Check the installed version to confirm it worked:
python -c "import anthropic; print(anthropic.__version__)"
Pin the version in requirements.txt or pyproject.toml once you've confirmed your code works against it. Anthropic updates the SDK regularly, and breaking changes do happen between major versions.
Setting your API key
The SDK looks for an ANTHROPIC_API_KEY environment variable by default. Set it in your shell:
export ANTHROPIC_API_KEY="sk-ant-..."
Or load it from a .env file using python-dotenv:
pip install python-dotenv
from dotenv import load_dotenv
load_dotenv()
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY automatically
Never hardcode the key in source files, and never commit .env to version control. If you're deploying to a serverless platform, set the key as a secret/environment variable in your platform's dashboard rather than baking it into the deployment package.
Making your first request
Once the client is initialized, sending a message is straightforward:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain what a Python virtual environment does."}
],
)
print(response.content[0].text)
A few things worth knowing at this stage:
max_tokensis required and caps the response length — it doesn't control input length.messagesis a list of turns; the SDK doesn't inject a system prompt automatically, so pass one explicitly with thesystemparameter if you need it.- The response object includes
usage(input/output token counts), which you'll want to log if you're tracking cost.
Configuring timeouts and retries
By default, the SDK retries transient failures (like network errors or 5xx responses) up to two times, and uses a reasonable default timeout. You can override both:
client = anthropic.Anthropic(
timeout=30.0,
max_retries=4,
)
For long-running requests — large documents, complex tool-use chains — increase the timeout rather than letting requests fail silently. For latency-sensitive endpoints, do the opposite and fail fast so your application can fall back to a cached response or a shorter prompt.
Streaming responses
For chat interfaces or anything where perceived latency matters, use streaming instead of waiting for the full response:
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about databases."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final_message = stream.get_final_message()
The stream.text_stream iterator yields text chunks as they arrive, and get_final_message() gives you the complete response object afterward, including usage stats, once streaming finishes.
Handling errors properly
Wrap requests in try/except blocks and handle the specific exception types the SDK exposes, rather than catching everything generically:
import anthropic
try:
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)
except anthropic.APIConnectionError as e:
print("Network error:", e)
except anthropic.RateLimitError as e:
print("Rate limited:", e)
except anthropic.APIStatusError as e:
print(f"API error {e.status_code}: {e.response}")
This matters more than it looks — rate limit errors and authentication errors need different handling, and a generic except Exception swallows the distinction you need to debug production issues.
If you don't have direct Anthropic API access
Some teams have a Claude subscription (Pro or Team) but not an Anthropic API key, or they want a simpler setup that includes usage tracking and per-application key management without managing billing dashboards themselves. In that case, a service like SubToAPI wraps Claude behind a standard HTTPS API with its own keys (sub_live_...), so your Python code talks to a normal REST endpoint instead of requiring separate Anthropic account provisioning.
The request shape mirrors the Messages API closely, so switching between them later is a small diff, not a rewrite:
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": 1024,
"messages": [{"role": "user", "content": "Hello"}]
}'
You can call this endpoint from Python with the standard requests library the same way you'd call any HTTP API — no separate SDK required. The quickstart covers key creation and your first call, messages documents the request format, and streaming covers server-sent events if you need incremental output. Plans start at €9/month with a free trial, listed on the pricing page.
Project structure recommendations
For anything beyond a script, isolate the client setup in one place:
# clients.py
import os
import anthropic
def get_client() -> anthropic.Anthropic:
api_key = os.environ["ANTHROPIC_API_KEY"]
return anthropic.Anthropic(api_key=api_key, timeout=30.0, max_retries=3)
Import get_client() wherever you need it instead of instantiating the client repeatedly. This makes it trivial to swap configuration (timeouts, base URL, retries) in one spot, and makes testing easier since you can mock a single function.
FAQ
Do I need a paid Anthropic account to use the Python client library? Yes, the anthropic package requires a valid API key tied to a billed Anthropic account. The library itself is free and open source, but every request consumes API credits.
Can I use the same Python client code with a different base URL? Yes. The Anthropic client accepts a base_url parameter, which lets you point requests at a compatible proxy or gateway without changing the rest of your code, as long as the endpoint implements the same request/response format.
What Python version does the Claude API client require? The official SDK supports Python 3.8 and above. Using a recent 3.10+ version is recommended since Anthropic tests primarily against current Python releases.