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 reply

Two 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 backoff

Separate 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

FAQ

Questions

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.

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.

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.

Cait Hitesh Scaled

Your trainer

Meet Hitesh Motwani

Hitesh Motwani is a globally recognised corporate AI trainer and generative-AI expert. He has trained 2,00,000+ professionals across 16+ countries on Claude, ChatGPT and generative AI, and advised leadership teams at Tata, Flipkart, Hitachi, Siemens, Adani and Marks & Spencer. Connect on LinkedIn →

Trusted by

Teams we’ve trained

TataJSW PaintsMitsui & Co.BirlasoftXebiaPiramal FinanceHPEAction Construction EquipmentIndoramaPharmedM Square MediaFlipkartHitachiAdaniSonyMahindra

…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.”

Sabyasachi DasGeneral Manager, Tata Teleservices
★★★★★

“The session was highly insightful and conducted in a very professional and interactive manner. Learnt about AI and excited to learn more!”

Rohan MankameDGM – Financial Planning, JSW Paints
★★★★★

“Highly recommended! Hands-on and directly useful — from making PPTs and strategic plans to building KRAs.”

Suneetha QureshiPresident, M Square Media
★★★★★

“Great work done by Mr Hitesh in the AI landscape — a true subject-matter expert. More power to him for spreading this knowledge.”

Vikram Sagar SaxenaAsst. Vice President, Pharmed Ltd
★★★★★

“I would recommend everyone to go through this session — it clarifies both what to expect from AI and where AI isn’t needed.”

Rahul AroraDeputy General Manager, Tata Tele Business Services
★★★★★

“Amazing session by Hitesh. The AI tools he shared are very helpful for day-to-day work.”

Varsha TaklikarDy. Manager, Mitsui & Co. India
★★★★★

“Mr Hitesh Motwani is a very informative trainer. The way he delivers training is awesome.”

Prem ChandDy. Manager – HR, Action Construction Equipment
★★★★★

“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.”

Alisha KhanProgram Coordinator, Q Academy
★★★★★

“A nice interactive session with a lot of new insights and the power of AI. This will help me save time in routine activities.”

Ramnath BandiSenior Manager – Engineering, JSW Paints
★★★★★

“A very good training session. AI can do wonders — we’ll implement it to create efficiency and save time.”

Ruchit PanchalDeputy Manager, Mitsui & Co.
★★★★★

“Hitesh was very informative and knowledgeable about AI tools. It will let me use my time far more effectively.”

Dagmar NoronhaOperations Manager, Q Academy (Toronto)
★★★★★

“Your session helped me walk into the world of magic.”

Partha ChowdhuryDHM, JSW Paints

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.