Build With Claude in Python
The official anthropic Python SDK is the easiest way to use Claude in your apps. This guide goes from your first message to production patterns: streaming, tool use, structured JSON output, prompt caching and error handling.
All examples use the current model IDs. Claude models are updated regularly, so check Anthropic's models page when you start a project.
🎯 Quick Answer (30-Second Read)
- Install:
pip install anthropic, then setANTHROPIC_API_KEY. - Call:
client.messages.create(model=..., max_tokens=..., messages=[...]). - Models:
claude-opus-5-5(default, most tasks),claude-sonnet-5-5(fast, high volume),claude-haiku-5-5(cheapest, simple tasks),claude-fable-5-1(most capable). - Stream long responses with
client.messages.stream(...). - Tools: decorate Python functions with
@beta_tooland lettool_runnerhandle the loop. - Structured output:
client.messages.parse(..., output_format=YourPydanticModel). - Save money: prompt caching with
cache_control.
Step 1: Install and Authenticate
pip install anthropic
export ANTHROPIC_API_KEY="sk-ant-..." # from console.anthropic.comimport anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environmentNever hard-code your key or commit it to Git.
Step 2: Your First Message
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
system="You are a helpful assistant who explains things simply.",
messages=[{"role": "user", "content": "Explain UPI in two sentences."}],
)
for block in response.content:
if block.type == "text":
print(block.text)response.content is a list of blocks (text, tool calls, and so on), so check each block's type.
How a Request Flows
→ run tool, send result back
Choosing a Model
| Model ID | Best for | Price (input / output per 1M tokens) |
|---|---|---|
claude-fable-5-1 |
Hardest reasoning and long agentic tasks | $10 / $50 |
claude-opus-5-5 |
Default for most work: coding, agents, analysis | $4 / $20 |
claude-sonnet-5-5 |
Fast, high-volume production workloads | $2 / $10 |
claude-haiku-5-5 |
Simple, very cheap, latency-sensitive tasks | $0.10 / $0.50 (up to 100K-token prompts) |
All of these have a 1M-token context window. See Claude API Pricing for caching and batch discounts.
Step 3: Multi-Turn Conversations
The API is stateless. Send the conversation history every time:
messages = [{"role": "user", "content": "My name is Asha."}]
reply = client.messages.create(model="claude-opus-5-5", max_tokens=4096, messages=messages)
messages.append({"role": "assistant", "content": reply.content})
messages.append({"role": "user", "content": "What's my name?"})
reply = client.messages.create(model="claude-opus-5-5", max_tokens=4096, messages=messages)Step 4: Streaming
For chat UIs and long answers, stream text as it's generated:
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
messages=[{"role": "user", "content": "Write a short story about a chai stall."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message() # full message + usage when doneStep 5: Tool Use (Function Calling)
Let Claude call your Python functions. The tool runner handles the back-and-forth loop:
from anthropic import beta_tool
@beta_tool
def get_train_status(train_number: str) -> str:
"""Get the live running status of an Indian Railways train.
Args:
train_number: The 5-digit train number, e.g. 12951.
"""
return f"Train {train_number} is running 10 minutes late." # call a real API here
runner = client.beta.messages.tool_runner(
model="claude-opus-5-5",
max_tokens=16000,
tools=[get_train_status],
messages=[{"role": "user", "content": "Is train 12951 on time?"}],
)
for message in runner: # each step until Claude is done
print(message.content)The docstring and type hints become the tool's description and schema, so write them clearly. (For MCP-based tools, see How to Build an MCP Server in Python.)
Step 6: Structured JSON Output
Get validated data back using a Pydantic model:
from pydantic import BaseModel
class Lead(BaseModel):
name: str
email: str
plan: str
wants_demo: bool
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content":
"Extract: Ravi (ravi@shop.in) wants the Pro plan and asked for a demo."}],
output_format=Lead,
)
lead = response.parsed_output
print(lead.name, lead.wants_demo) # Ravi TrueStep 7: Prompt Caching
If you send the same long instructions or documents repeatedly, cache them:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
cache_control={"type": "ephemeral"}, # cache the stable prefix automatically
system=LONG_COMPANY_HANDBOOK, # same text on every request
messages=[{"role": "user", "content": "What is the leave policy?"}],
)
print(response.usage.cache_read_input_tokens) # > 0 when the cache is hitStep 8: Error Handling
The SDK automatically retries rate limits, server errors and connection problems (2 retries by default). Handle what remains:
try:
response = client.messages.create(
model="claude-opus-5-5", max_tokens=4096,
messages=[{"role": "user", "content": "Hi"}],
)
except anthropic.BadRequestError as e:
print("Fix the request:", e.message)
except anthropic.AuthenticationError:
print("Check your API key")
except anthropic.RateLimitError:
print("Rate limited, slow down or retry later")
except anthropic.APIStatusError as e:
print("API error", e.status_code)
except anthropic.APIConnectionError:
print("Network problem")Configure retries and timeouts on the client: anthropic.Anthropic(max_retries=5, timeout=120.0).
Production Checklist
- Key in environment variables or a secrets manager, never in code
- Stream long outputs to avoid timeouts and improve UX
- Check
response.stop_reason(e.g.max_tokens,refusal) before using output - Cache long, repeated prompts
- Log
response.usageto track cost - Use the Batches API for large offline jobs (lower price, asynchronous)
Frequently Asked Questions
How do I use the Claude API in Python?
Install the anthropic package with pip, set the ANTHROPIC_API_KEY environment variable, create a client with anthropic.Anthropic(), and call client.messages.create with a model ID, max_tokens and a list of messages. Read the text from the returned content blocks.
Which Claude model should I use?
Claude Opus 5.5 (claude-opus-5-5) is a strong default for most tasks. Use Claude Sonnet 5.5 for faster, high-volume workloads, Claude Haiku 5.5 for simple, cost-sensitive tasks, and Claude Fable 5.1 for the most demanding reasoning and long-running agent work.
How do I get JSON output from Claude in Python?
Define a Pydantic model and call client.messages.parse with output_format set to that model. The SDK validates the response, and response.parsed_output contains a typed instance of your model.
Conclusion
With the anthropic SDK, a basic Claude call is a few lines of Python. From there, stream long responses, let the tool runner handle function calling, use messages.parse for validated JSON, cache repeated context to cut costs, and rely on built-in retries plus typed exceptions for robust production code.
Sources
- Anthropic docs: Python SDK
- Anthropic docs: Models overview
- Anthropic docs: Tool use
- Anthropic docs: Prompt caching
Last verified: 2 November 2026.
Related reads: Claude API Pricing · Claude Prompt Caching Guide · Claude Models Explained · Tokenization in LLMs Explained
I write about building with AI and how real products work. Follow on LinkedIn or X, or invite me to speak.