Anthropic Python SDK is the official library for working with Claude. It hides the complexity of raw HTTP requests, adds type annotations, and automatically handles transient network errors.
Installation
uv add anthropic
Creating a Client
import anthropic
# Passing the key explicitly:
client = anthropic.Anthropic(api_key="sk-ant-api03-...")
# Or the SDK reads ANTHROPIC_API_KEY from the environment automatically:
client = anthropic.Anthropic()
Your First Request
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hi! Explain what an API is."}
]
)
print(message.content[0].text)
The response text lives in message.content[0].text — not in message.text. This is intentional: Claude can return multiple content blocks (text, tool calls, JSON), so content is a list.
Request Structure
client.messages.create(
model="claude-sonnet-4-6", # required
max_tokens=1024, # required
system="You are a Python tutor.", # optional — sets the role
temperature=0.7, # optional — 0.0–1.0
messages=[ # required
{"role": "user", "content": "First question"},
{"role": "assistant", "content": "First answer"},
{"role": "user", "content": "Second question"},
]
)
Roles in messages must alternate: user → assistant → user → …
Response Structure
message.id # unique request ID
message.model # model that responded
message.stop_reason # "end_turn" or "max_tokens"
message.content[0].text # response text
message.usage.input_tokens # request tokens (billing)
message.usage.output_tokens # response tokens (billing)
Available Models (2026)
| Model | Use Case |
|---|---|
claude-haiku-4-5 |
Simple tasks, high traffic |
claude-sonnet-4-6 |
Most tasks — optimal balance |
claude-opus-4-7 |
Complex tasks, deep analysis |
Error Handling
try:
message = client.messages.create(...)
except anthropic.AuthenticationError:
print("Invalid API key. Check your .env")
except anthropic.RateLimitError:
print("Rate limit exceeded — wait a moment")
except anthropic.APIConnectionError:
print("No connection to the Anthropic API")
except anthropic.APIStatusError as e:
print(f"API error {e.status_code}: {e.message}")
Automatic Retries
The SDK automatically retries on 429 Too Many Requests and 5xx Server Error:
# Configure retry behavior:
client = anthropic.Anthropic(
api_key=API_KEY,
max_retries=3, # default is 2
timeout=30.0, # timeout in seconds
)
Messages API vs Legacy API
client.messages.create() is the Messages API — the current way to work with Claude. The old completions API is deprecated and does not support new features (tool use, streaming, vision).
Always use the Messages API.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!