Claude API Streaming Response: Python Example Guide
Streaming lets your Python app display Claude's response token by token instead of waiting for the full completion. This matters for chat UIs, CLI tools, and anything where perceived latency affects user experience — a response that starts appearing after 300ms feels faster than one that arrives all at once after 4 seconds, even if the total generation time is identical.
Below is a working Claude API streaming response Python example using plain requests, followed by the official SDK version, error handling patterns, and notes on what changes if you're calling an API that re-exposes Claude access (like SubToAPI) instead of Anthropic directly.
How streaming works under the hood
Claude's streaming endpoint sends Server-Sent Events (SSE) over a single HTTP connection. Each event is a JSON chunk prefixed with event: and data: lines. The client reads the stream incrementally and reconstructs the message from a sequence of event types:
message_start— metadata about the response (model, id, usage so far)content_block_start— a new content block beginscontent_block_delta— the actual text fragments, arriving repeatedlycontent_block_stop— the block is completemessage_delta— final usage stats and stop reasonmessage_stop— the stream is done
You don't need to parse raw SSE by hand in most cases — both the Anthropic SDK and requests with iter_lines() handle this cleanly.
Minimal example with requests
import requests
import json
import os
API_KEY = os.environ["ANTHROPIC_API_KEY"]
def stream_claude(prompt: str):
url = "https://api.anthropic.com/v1/messages"
headers = {
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
}
payload = {
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"stream": True,
"messages": [{"role": "user", "content": prompt}],
}
with requests.post(url, headers=headers, json=payload, stream=True) as resp:
resp.raise_for_status()
for line in resp.iter_lines(decode_unicode=True):
if not line or not line.startswith("data:"):
continue
data = line[len("data:"):].strip()
if data == "[DONE]":
break
event = json.loads(data)
if event.get("type") == "content_block_delta":
text = event["delta"].get("text", "")
print(text, end="", flush=True)
stream_claude("Explain streaming in one paragraph.")
This is deliberately low-level so you can see exactly what's happening: open a connection with stream=True, iterate line by line, skip anything that isn't a data: event, parse the JSON, and pull out text deltas. Everything else (usage metadata, stop reasons, tool call fragments) lives in the other event types if you need them.
Using the official SDK
The anthropic Python SDK wraps this into a context manager that's easier to read:
from anthropic import Anthropic
client = Anthropic()
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Explain streaming in one paragraph."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final_message = stream.get_final_message()
print("\n\nStop reason:", final_message.stop_reason)
stream.text_stream yields just the text deltas, and get_final_message() gives you the fully assembled message afterward — useful for logging token usage or the final stop reason without re-parsing anything manually.
Handling errors mid-stream
Streaming connections can drop or return mid-stream errors (rate limits, overloaded errors, context length issues). Wrap the loop so a partial failure doesn't crash your app or leave the UI hanging:
import anthropic
try:
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
) as stream:
for text in stream.text_stream:
yield text
except anthropic.APIStatusError as e:
print(f"API error {e.status_code}: {e.message}")
except anthropic.APIConnectionError:
print("Connection dropped mid-stream — retry with backoff")
For production code, add a retry with exponential backoff on APIConnectionError and overloaded_error, and make sure your frontend can handle a stream that stops without a clean message_stop event.
Streaming through a proxy or gateway API
If you're calling Claude through a layer that sits in front of Anthropic — a proxy, an internal gateway, or a service like SubToAPI that turns your existing Claude access into a standard HTTPS API — the Python code barely changes. You swap the base URL and auth header, and the SSE format stays the same because SubToAPI mirrors Anthropic's Messages API shape:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"stream": true,
"messages": [{"role": "user", "content": "Explain streaming in one paragraph."}]
}'
In Python, that's the same requests loop from above with url = "https://api.subtoapi.app/v1/messages" and Authorization: Bearer <key> instead of x-api-key. This is useful if you don't have direct Anthropic API billing set up but already have Claude access through another plan — you get application API keys, streaming, and usage metadata without re-architecting your client code. See the streaming docs and quickstart for the exact request/response reference.
A few practical tips
- Buffer on word boundaries, not characters. Printing every raw delta can split words awkwardly in terminal output; batch small deltas if you're rendering to a UI.
- Track
usagefrommessage_delta. It's the only reliable place to get final input/output token counts in a streamed response. - Set a read timeout. Streaming connections can hang if the server stalls; a client-side timeout (e.g., 60–120s of inactivity) prevents orphaned connections.
- Don't parse JSON per character. Always parse complete
data:lines — partial JSON will throw decode errors.
Questions
Does streaming cost more than non-streaming requests? No. Token usage and pricing are identical — streaming only changes delivery, not the number of input or output tokens billed.
Can I stream tool use (function calling) responses? Yes. Tool calls arrive as content_block_start/delta events with a tool_use type; you accumulate the JSON fragments until the block closes, then parse the complete arguments. See tool use docs for the event structure.
What's the simplest way to test streaming without writing a client? Use curl with -N (no buffering) against the Messages endpoint with "stream": true — you'll see raw SSE events printed to the terminal, which is the fastest way to inspect the event shape before writing Python code.