← Blog

Claude API Python Async Streaming Example

2026-11-23 · 4 min read · SubToAPI Team

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:

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

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.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →