Claude API Python Async Streaming Example
Streaming lets you render Claude's response token by token instead of waiting for the full completion, which matters a lot for chat UIs and CLIs where perceived latency is the difference between a product that feels alive and one that feels stuck. In Python, the cleanest way to do this is with httpx's async client and asyncio, consuming Server-Sent Events (SSE) as they arrive from the API.
Below is a complete, working async streaming example against an Anthropic-compatible Messages endpoint, followed by the parts people usually get wrong: backpressure, partial JSON, cancellation, and error handling mid-stream.
Why async for streaming
A synchronous requests call blocks your whole thread until the connection closes. That's fine for single-shot scripts, but it breaks down the moment you need to:
- Stream to multiple clients concurrently (e.g., a FastAPI endpoint serving many users)
- Cancel a generation early if the user navigates away
- Run several Claude calls in parallel without spawning threads
asyncio plus an async HTTP client solves all three. You get one event loop handling many open connections, each yielding chunks as they arrive, with cooperative cancellation built in.
Minimal async streaming example
import asyncio
import json
import httpx
API_KEY = "sk-your-key-here"
API_URL = "https://api.anthropic.com/v1/messages"
async def stream_claude(prompt: str):
headers = {
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
}
payload = {
"model": "claude-sonnet-4-20250514",
"max_tokens": 1024,
"stream": True,
"messages": [{"role": "user", "content": prompt}],
}
async with httpx.AsyncClient(timeout=60.0) as client:
async with client.stream("POST", API_URL, headers=headers, json=payload) as response:
response.raise_for_status()
async for line in response.aiter_lines():
if not line or not line.startswith("data:"):
continue
data = line.removeprefix("data: ").strip()
if data == "[DONE]":
break
event = json.loads(data)
if event.get("type") == "content_block_delta":
delta = event["delta"].get("text", "")
print(delta, end="", flush=True)
asyncio.run(stream_claude("Explain async generators in three sentences."))
This parses the SSE stream line by line, filters for content_block_delta events, and prints text as it arrives. The key async primitives doing the work are client.stream() as an async context manager and response.aiter_lines() as an async iterator — neither blocks the event loop while waiting for network data.
Turning it into a proper async generator
Printing inline is fine for a demo, but in real code you want a generator you can async for over, so callers can pipe chunks into a websocket, a queue, or a UI framework.
async def stream_claude_chunks(prompt: str):
headers = {
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
}
payload = {
"model": "claude-sonnet-4-20250514",
"max_tokens": 1024,
"stream": True,
"messages": [{"role": "user", "content": prompt}],
}
async with httpx.AsyncClient(timeout=60.0) as client:
async with client.stream("POST", API_URL, headers=headers, json=payload) as response:
response.raise_for_status()
async for line in response.aiter_lines():
if not line or not line.startswith("data:"):
continue
data = line.removeprefix("data: ").strip()
if data == "[DONE]":
return
event = json.loads(data)
if event.get("type") == "content_block_delta":
yield event["delta"].get("text", "")
async def main():
async for chunk in stream_claude_chunks("Write a haiku about Python."):
print(chunk, end="", flush=True)
asyncio.run(main())
This pattern composes well. You can wrap it in a FastAPI StreamingResponse, feed it into a websocket send loop, or run several generators concurrently with asyncio.gather.
Common pitfalls
- Not handling
[DONE]or malformed JSON: some events are pings or metadata with nodeltafield. Always checkevent.get("type")before indexing into the dict. - Forgetting
response.raise_for_status(): a 4xx/5xx response still opens a stream connection; without this check you'll silently parse an error body as if it were content. - Blocking calls inside the loop: if you call a synchronous function (e.g., writing to a file without
aiofiles) insideasync for, you block the event loop for every other concurrent stream. Offload blocking work withasyncio.to_thread. - No timeout: long-running generations without a client timeout can hang a connection indefinitely if the server stalls. Set
timeoutexplicitly on the client. - Cancellation not propagated: if a user disconnects, make sure you exit the
async with client.stream(...)block — Python's context manager will close the HTTP connection and stop billing for tokens you no longer need.
When you don't want to manage this yourself
Handling SSE parsing, reconnects, timeouts, and partial JSON correctly across every endpoint in your app adds up fast, especially once you're running this logic in production across multiple services. SubToAPI wraps Claude access behind a standard HTTPS API with its own streaming support, so your Python client just opens a connection to https://api.subtoapi.app/v1/messages with stream: true and consumes the same SSE format shown above — no separate key management or provider-specific quirks to track down.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-20250514",
"max_tokens": 1024,
"stream": true,
"messages": [{"role": "user", "content": "Hello"}]
}'
Plans start at €9/month on the Solo tier, with Team and Scale tiers for shared API keys and usage visibility across a team. Full details are in the streaming docs and pricing page, and you can get a key from signup to try it against your own async client.
Questions
Does httpx support streaming natively, or do I need another library? httpx.AsyncClient supports streaming out of the box via client.stream(), which returns an async context manager you iterate with aiter_lines() or aiter_bytes(). No extra SSE library is required for basic use cases.
Can I run multiple Claude streams concurrently in one Python process? Yes — because each stream is an async generator backed by non-blocking I/O, you can run many of them concurrently with asyncio.gather or asyncio.TaskGroup, limited only by your connection pool and rate limits.
What's the difference between streaming and polling for long responses? Streaming delivers partial output over a single open connection as it's generated, giving low time-to-first-token. Polling requires repeated requests to check status and only works with APIs that support async job submission, which adds latency and complexity for no real benefit in typical chat use cases.