Python SDK Basics
9 examples to get you started with the Anthropic Python SDK - 6 basic and 3 intermediate.
Search across all documentation pages
9 examples to get you started with the Anthropic Python SDK - 6 basic and 3 intermediate.
pip install anthropic.export ANTHROPIC_API_KEY=sk-ant-....Add the official package to your project with pip.
pip install anthropicanthropic package and its dependencies, including httpx for HTTP transport.requirements.txt (anthropic>=0.40,<1.0) for reproducible builds.Construct a client once, reusing the API key from the environment.
import anthropic
client = anthropic.Anthropic()Anthropic() reads the ANTHROPIC_API_KEY environment variable automatically.api_key="sk-ant-..." explicitly only when you cannot use an environment variable, for example when a key is loaded from a secrets manager at runtime.Related: The Anthropic Python SDK Mental Model - how the client fits into the SDK's design
Call the Messages API with a model, a token limit, and a list of messages.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "In one sentence, what is a Python decorator?"}
],
)
print(message.content[0].text)model selects which Claude model answers the request; claude-sonnet-5 is a strong default for most workloads.max_tokens caps the length of the response, not the length of your input.messages is a list of turns; the first entry must have role="user".message.content is a list of content blocks, not a single string.
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Name three prime numbers."}],
)
for block in message.content:
if block.type == "text":
print(block.text)content is always a list.block.type == "text" before reading .text avoids errors when a response contains non-text blocks.message.content[0].text is a common shortcut once you know the shape of your responses.Use the system parameter to steer the model's behavior for the whole conversation.
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
system="You are a terse Python tutor. Answer in one short paragraph.",
messages=[{"role": "user", "content": "What is a generator?"}],
)
print(message.content[0].text)system is a top-level parameter, separate from messages, and applies to the entire request.system prompt is also what makes prompt caching effective later on.max_tokens is a hard ceiling on the response, and hitting it truncates output.
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=100,
messages=[{"role": "user", "content": "Write a 500-word essay on Python typing."}],
)
print(message.stop_reason) # "max_tokens" if the essay was cut off
print(message.content[0].text)stop_reason tells you why generation stopped: "end_turn" for a natural finish, "max_tokens" for a truncation.max_tokens too low for the task silently cuts off the answer rather than raising an error.Related: Streaming Responses with the Python SDK - avoid timeouts on large responses
The API is stateless - you resend the full conversation history on every call.
import anthropic
client = anthropic.Anthropic()
messages = [
{"role": "user", "content": "My favorite language is Python."},
]
first = client.messages.create(model="claude-sonnet-5", max_tokens=200, messages=messages)
messages.append({"role": "assistant", "content": first.content[0].text})
messages.append({"role": "user", "content": "What did I say my favorite language was?"})
second = client.messages.create(model="claude-sonnet-5", max_tokens=200, messages=messages)
print(second.content[0].text)messages list you send.messages before adding the next user turn, so the model sees its own prior answer.role="user" and generally alternate user/assistant.Catch the SDK's specific exception classes instead of a single broad except.
import anthropic
client = anthropic.Anthropic()
try:
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)
except anthropic.RateLimitError:
print("Rate limited - back off and retry later.")
except anthropic.APIConnectionError:
print("Network error reaching the API.")
except anthropic.APIStatusError as e:
print(f"API returned an error: {e.status_code} {e.message}")RateLimitError, APIConnectionError, and APIStatusError are distinct classes for distinct failure modes; catch the most specific one first.Related: Python SDK Exception Types at a Glance - the full exception-to-strategy mapping
Set client-wide defaults for how long to wait and how many times to retry.
import anthropic
client = anthropic.Anthropic(
max_retries=4,
timeout=30.0,
)
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Summarize the plot of a short story about a lighthouse."}],
)
print(message.content[0].text)max_retries controls how many times the SDK automatically retries a transient failure before raising; the default is 2.timeout is in seconds for the Python SDK and applies per request unless overridden.client.with_options(...) to override either setting for a single call without changing the client's defaults.Related: Python SDK Retry and Timeout Configuration Reference - every setting, compared side by side
Stack versions: Written against the Claude model lineup current as of ~June 2026 - Claude Fable 5, Claude Opus 4.8, Claude Sonnet 5 (the default), and Claude Haiku 4.5 - and the official
anthropicPython SDK (latest 0.x release). Model names, SDK versions, and pricing move quickly - verify current specifics at platform.claude.com/docs before relying on them.
Reviewed by Chris St. John·Last updated Jul 19, 2026