Claude API Integration with Python
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Python is Anthropic's best-supported SDK language and the natural choice for scripts, data jobs and AI-heavy back ends. This lesson builds a small FastAPI service with an async client: one JSON endpoint, one streaming endpoint, validated input, safe errors and tests that never touch the real API.
Learning objectives
- Use the async client (
AsyncAnthropic) correctly in a web service.
- Expose JSON and server-sent-event endpoints with FastAPI.
- Validate input with Pydantic and map SDK errors to HTTP responses.
- Test the service offline.
Prerequisites
- Python 3.9 or later and lessons 2.6 and 2.7.
Architecture
Browser / client --POST /ask, /ask/stream--> FastAPI app
| AsyncAnthropic (shared, retries, timeout)
v
api.anthropic.com
One AsyncAnthropic client is created at start-up and shared by all requests. It reuses connections, and its max_retries and timeout settings apply everywhere.
Step 1: set up
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic fastapi "uvicorn[standard]" pytest httpx
export ANTHROPIC_API_KEY="your-api-key-here"
# .env.example (committed; no real key)
ANTHROPIC_API_KEY=
ANTHROPIC_MODEL=claude-sonnet-5-5
Step 2: the application
import json
import os
import anthropic
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5")
SYSTEM = "You are a concise assistant for a web development blog. Answer in under 120 words."
app = FastAPI(title="Claude demo API")
# One shared async client per process; it reads ANTHROPIC_API_KEY from the environment.
client = anthropic.AsyncAnthropic(max_retries=2, timeout=60.0)
class AskRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
class AskResponse(BaseModel):
answer: str
stop_reason: str
input_tokens: int
output_tokens: int
@app.post("/ask", response_model=AskResponse)
async def ask(body: AskRequest) -> AskResponse:
try:
message = await client.messages.create(
model=MODEL,
max_tokens=500,
system=SYSTEM,
messages=[{"role": "user", "content": body.prompt}],
)
except anthropic.RateLimitError:
raise HTTPException(status_code=429, detail="Too many requests, try again shortly.")
except (anthropic.APIConnectionError, anthropic.APIStatusError):
raise HTTPException(status_code=503, detail="The assistant is unavailable right now.")
return AskResponse(
answer="".join(b.text for b in message.content if b.type == "text"),
stop_reason=message.stop_reason or "",
input_tokens=message.usage.input_tokens,
output_tokens=message.usage.output_tokens,
)
@app.post("/ask/stream")
async def ask_stream(body: AskRequest) -> StreamingResponse:
async def events():
try:
async with client.messages.stream(
model=MODEL,
max_tokens=800,
system=SYSTEM,
messages=[{"role": "user", "content": body.prompt}],
) as stream:
async for text in stream.text_stream:
yield "data: " + json.dumps({"t": text}) + "\n\n"
yield "event: done\ndata: {}\n\n"
except anthropic.APIError:
# The 200 header is already sent, so report the failure inside the stream.
yield 'event: error\ndata: {"message": "The assistant stopped unexpectedly."}\n\n'
return StreamingResponse(events(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
Points worth noticing:
AskRequest uses Field(min_length=1, max_length=4000), so FastAPI rejects empty or oversized prompts with a 422 before any API call happens.
- The two
except clauses are ordered specific-to-general, and neither returns the exception text to the caller.
- The stream endpoint catches
anthropic.APIError inside the generator, because the 200 status has already been sent when an error occurs mid-stream. The error is sent as an event: error so the browser can react.
stream.text_stream is an async iterator, so the whole path stays non-blocking.
Run it with uvicorn app:app --reload and try:
curl -s localhost:8000/ask -H 'content-type: application/json' -d '{"prompt":"What is FastAPI?"}'
curl -N localhost:8000/ask/stream -H 'content-type: application/json' -d '{"prompt":"Write a haiku about APIs"}'
The streaming events match the format the JavaScript reader from lesson 2.6 expects: data: {"t": "..."} lines, then event: done.
Step 3: tests that never call the API
The Anthropic SDK reads ANTHROPIC_BASE_URL, so tests can point the client at a local fake server, or you can replace methods with monkeypatch. This file checks the happy path, validation, the stream format and the rate-limit mapping:
import anthropic
import httpx
import pytest
from fastapi.testclient import TestClient
import app as app_module
@pytest.fixture
def client():
return TestClient(app_module.app)
def test_ask_returns_answer_and_usage(client, monkeypatch):
r = client.post("/ask", json={"prompt": "What is FastAPI?"})
assert r.status_code == 200
body = r.json()
assert body["answer"] == "Hello from the mock."
assert body["input_tokens"] == 12 and body["output_tokens"] == 6
def test_ask_validates_prompt(client):
assert client.post("/ask", json={"prompt": ""}).status_code == 422
assert client.post("/ask", json={"prompt": "x" * 4001}).status_code == 422
def test_stream_emits_sse_events(client):
with client.stream("POST", "/ask/stream", json={"prompt": "Hi"}) as r:
text = "".join(r.iter_text())
assert 'data: {"t": "Hello"}' in text
assert "event: done" in text
def test_rate_limit_becomes_429(client, monkeypatch):
async def boom(**kwargs):
raise anthropic.RateLimitError("slow down", response=httpx.Response(429, request=httpx.Request("POST", "http://x")), body=None)
monkeypatch.setattr(app_module.client.messages, "create", boom)
assert client.post("/ask", json={"prompt": "hi"}).status_code == 429
All four tests passed against a mock Claude server. In a real project you would run a tiny fake server in a fixture, or monkeypatch app.client.messages.create and app.client.messages.stream as the last test does.
Sync or async?
Use AsyncAnthropic inside async frameworks such as FastAPI, so a slow model call does not block other requests. Use the plain Anthropic client in scripts, notebooks, Django views and background workers where blocking is fine. The two clients share the same methods and parameters.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A data team keeps their pipeline in Python and needs a small internal service so a Laravel app can ask Claude to classify tickets. They deploy the FastAPI app behind the company network, with the key in the host's secret store. Laravel calls /ask with a shared token; the service validates, calls Claude, logs token counts, and returns only the label. Swapping the model means changing ANTHROPIC_MODEL and restarting.
Common errors and solutions
| Symptom | Cause | Fix |
RuntimeWarning: coroutine ... was never awaited | Forgot await on client.messages.create with the async client. | Add await. |
| Whole server stalls under load | Used the sync client inside an async def endpoint. | Use AsyncAnthropic. |
| Stream shows everything at the end | A proxy is buffering. | Send X-Accel-Buffering: no and configure the proxy. |
| 422 on every request | Client did not send JSON with a prompt field. | Send content-type: application/json and the right body. |
AuthenticationError at runtime | Process started without ANTHROPIC_API_KEY. | Export it for the process, or load a .env file. |
Security considerations
- Authenticate callers (an API token, an identity-aware proxy or mutual TLS); an open endpoint spends your money.
- Keep input limits and add rate limiting (for example, a reverse proxy or a library such as slowapi).
- Do not return exception messages; they can carry request IDs and internals.
- Run with a restricted service account and keep the key out of the image and the repository.
Performance and cost considerations
- One shared client; do not create one per request.
- Set an explicit
timeout; use streaming for long answers.
- Log
input_tokens and output_tokens per request (the response model above returns them) and feed them into the cost tracker from lesson 2.9.
Key takeaways
- Use
AsyncAnthropic in async web services, one shared instance.
- Validate with Pydantic, map SDK errors to safe HTTP responses.
- Report mid-stream errors in-band.
- Test offline by pointing
ANTHROPIC_BASE_URL at a fake or by monkeypatching.
Lesson recap: validate, share one async client, map errors safely and test without the real API.
Knowledge check
- Why use
AsyncAnthropic instead of Anthropic inside a FastAPI endpoint?
- Why is the stream's error handling inside the generator?
- Where does FastAPI reject a 4,001-character prompt?
- How can tests avoid the real API?
- Why create the client once at start-up?
Answers and explanations
- A blocking call inside an
async def endpoint stalls the event loop for every other request. The async client awaits instead.
- By the time an error occurs, the 200 status line has been sent, so the only way to tell the client is another event in the stream.
- In request validation (the Pydantic
max_length), returning 422 before any Claude call.
- Set
ANTHROPIC_BASE_URL to a local fake server, or monkeypatch the client methods.
- It reuses connections and applies the same retry and timeout settings to every request.
Official references and further reading
Related tutorials