Blog · Claude API
Using the Claude API with Python: Setup to Production
A hands-on path through the official anthropic Python SDK: installation, first calls, conversations, streaming, robust error handling, and the patterns that make integrations production-ready.
Python is the default language of applied AI, and Anthropic’s official anthropic SDK reflects that: it is well-typed, retries transient failures automatically, ships sync and async clients, and includes helpers for streaming, tool use, and structured outputs. You can go from empty virtualenv to a working Claude integration in a coffee break — but going from working to production-grade takes a few more deliberate steps.
This tutorial follows the sequence we teach in developer workshops: install and authenticate, master the basic request-response shape, manage multi-turn conversations, add streaming, then harden everything with proper error handling and cost instrumentation. Every snippet is self-contained and uses current model IDs, so you can follow along in a REPL.
Install, Authenticate, Verify
Setup is three commands. Install the SDK, export your key from console.anthropic.com, and verify with a one-liner:
pip install anthropic
export ANTHROPIC_API_KEY="sk-ant-..."import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
msg = client.messages.create(
model="claude-sonnet-5", max_tokens=256,
messages=[{"role": "user", "content": "Say hello in Hindi."}],
)
print(msg.content[0].text)Never pass the key as a string literal in code — the zero-argument constructor reading the environment is the correct pattern for every environment from laptop to Kubernetes. For async applications, anthropic.AsyncAnthropic() exposes the identical surface with await.
The Request-Response Shape in Detail
Three parameters are required — model, max_tokens, messages — and two optional ones do most of the steering: system (role and rules, kept separate from user content) and temperature-style behavior controls where the model supports them. Choose the model by task: claude-haiku-4-5 for high-volume simple work, claude-sonnet-5 as the default, claude-opus-4-8 or claude-fable-5 for the hardest reasoning (see our model guide).
Responses are Pydantic objects. The two fields to internalize:
- content — a list of typed blocks; always check block.type == “text” rather than assuming index zero is text.
- usage — exact input and output token counts; log this on every call.
Also check stop_reason: “max_tokens” means your output was truncated and the ceiling needs raising.
Multi-Turn Conversations
The API is stateless, so your application owns the history: append each assistant reply to a list and resend it. A minimal conversation manager is a dozen lines:
history = []
def chat(user_text: str) -> str:
history.append({"role": "user", "content": user_text})
msg = client.messages.create(
model="claude-sonnet-5", max_tokens=1024,
system="You are a concise engineering assistant.",
messages=history,
)
reply = next(b.text for b in msg.content if b.type == "text")
history.append({"role": "assistant", "content": reply})
return replyTwo rules: the first message must be a user turn, and history is re-billed as input every call — so trim or summarize old turns in long sessions, and put a cache_control breakpoint on your stable system prompt to make repeated context cheap.
Streaming Responses
For anything user-facing, stream. The SDK’s context-manager helper hides the server-sent-events plumbing and still gives you the complete message at the end:
with client.messages.stream(
model="claude-sonnet-5", max_tokens=2048,
messages=[{"role": "user", "content": "Draft a REST API design doc."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print(final.usage.output_tokens)Streaming is not just UX polish: for large max_tokens values the SDK requires it, because a long non-streaming request risks HTTP timeouts. Rule of thumb — stream anything that might exceed a few thousand output tokens, and always call get_final_message() when you need usage data or the assembled text.
Error Handling That Survives Production
The SDK raises typed exceptions per HTTP status and auto-retries rate limits and server errors with exponential backoff (configurable via max_retries). Catch specific classes, most specific first — never string-match error messages:
try:
msg = client.messages.create(**params)
except anthropic.RateLimitError:
... # queue or shed load; SDK already retried
except anthropic.APIStatusError as e:
log.error("api_error", status=e.status_code)
except anthropic.APIConnectionError:
... # network problem — retry with backoffSeparate retryable failures (429, 5xx, connection errors) from non-retryable ones (400 bad request, 404 wrong model ID) in your handling — retrying a malformed request just burns quota. Log the request ID from failed responses; Anthropic support can trace it end-to-end.
Production Patterns: Cost, Config, and Beyond
The last mile is operational discipline:
- Instrument usage: emit input, output, and cache-read token counts as metrics per endpoint; cost regressions become visible in hours, not on the invoice.
- Externalize model IDs and prompts: config-driven models make upgrades a reviewed change; versioned prompts make regressions bisectable.
- Cache aggressively: stable system prompts and tool definitions belong before a cache breakpoint.
- Batch the batchable: nightly enrichment and eval runs go through the Batches API at a steep discount.
- Timeouts: the default is generous; set explicit per-request timeouts in latency-sensitive paths via client.with_options(timeout=…).
Teams that want this full arc — from first call through tool use, MCP, and agents — compressed into a guided program can look at our Claude API & MCP training or the Claude Code Bootcamp.
Key takeaways
- Install with pip install anthropic and authenticate via the ANTHROPIC_API_KEY environment variable — never hardcode keys.
- Responses are lists of typed content blocks — check block.type instead of assuming content[0] is text.
- The API is stateless: your code owns conversation history, and long histories should be trimmed and cached.
- Stream anything long or user-facing; the SDK's stream helper plus get_final_message() gives you both live tokens and final usage.
- Catch typed exceptions (RateLimitError, APIStatusError, APIConnectionError) and let the SDK's built-in backoff handle transient failures.
- Externalize model IDs and prompts into config, and log token usage per endpoint from day one.
FAQ
Questions
Which Python version and packages do I need for the Claude API?
A currently supported Python 3 release and the official anthropic package are all you need — it bundles typed models and HTTP handling. Add pydantic if you want schema-validated structured outputs, and use the built-in AsyncAnthropic client for asyncio applications rather than wrapping the sync client in threads.
How do I keep a conversation going across multiple requests?
Store the message list yourself. Append each user turn, call the API with the full list, then append the assistant reply. The first message must be from the user. For long sessions, summarize or drop older turns and use prompt caching on the stable prefix so repeated history costs a fraction of full price.
Do I need to write my own retry logic for rate limits?
Usually not. The SDK automatically retries rate-limit and server errors with exponential backoff, configurable through max_retries. Add your own logic only for application-level concerns — queueing work during sustained limits, circuit breakers, or falling back to a different model tier when latency budgets are tight.
Who delivers it
Anthropic-certified Claude trainers
Every programme is delivered by Anthropic Claude Certified trainers who use Claude daily on live client work — engineering, analysis, research and content. We have trained 200,000+ professionals across 20+ countries for 600+ enterprise clients, including Tata Group, Adani, Siemens, GE Aerospace, HUL, Flipkart and Air India.
- Anthropic Claude Certified trainers, not generalist AI speakers
- 200,000+ professionals trained across 20+ countries
- 600+ enterprise clients, from BFSI and manufacturing to public sector
- Delivered in English, Hindi and Hinglish
Trusted by
Teams we’ve trained
…and 200+ organisations, across 16+ countries.
What participants say
Real feedback from real sessions
Verified feedback collected from participants across corporate sessions — average rating 4.8/5.
“A very productive session for working professionals. A must-do.”
“The session was highly insightful and conducted in a very professional and interactive manner. Learnt about AI and excited to learn more!”
“Highly recommended! Hands-on and directly useful — from making PPTs and strategic plans to building KRAs.”
“Great work done by Mr Hitesh in the AI landscape — a true subject-matter expert. More power to him for spreading this knowledge.”
“I would recommend everyone to go through this session — it clarifies both what to expect from AI and where AI isn’t needed.”
“Amazing session by Hitesh. The AI tools he shared are very helpful for day-to-day work.”
“Mr Hitesh Motwani is a very informative trainer. The way he delivers training is awesome.”
“Mr Hitesh Motwani delivered a valuable, informative session and showed us exactly how to use AI tools to enhance our work. Thank you so much.”
“A nice interactive session with a lot of new insights and the power of AI. This will help me save time in routine activities.”
“A very good training session. AI can do wonders — we’ll implement it to create efficiency and save time.”
“Hitesh was very informative and knowledgeable about AI tools. It will let me use my time far more effectively.”
“Your session helped me walk into the world of magic.”
Explore more
Keep going with Claude AI training
Work with us
Bring Claude AI training to your team
Tell us your team, tools and goals and we will send a fixed proposal — usually within one business day.