Claude API cheatsheet
Claude API: Streaming
4 common Claude API tasks.
Stream text (Python)
Print text as it is generated. Use streaming for long outputs and high max_tokens, which avoids request timeouts.
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
messages=[{"role": "user", "content": "Write a story"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Stream and get the full message
Stream for the timeout benefits, then read the complete message at the end.
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
messages=[{"role": "user", "content": "Write a long report"}],
) as stream:
message = stream.get_final_message()
print(message.usage.output_tokens)
Stream asynchronously
Use the async client with async with and async for.
async_client = anthropic.AsyncAnthropic()
async with async_client.messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
messages=[{"role": "user", "content": "Write a story"}],
) as stream:
async for text in stream.text_stream:
print(text, end="", flush=True)
Stream in TypeScript
Subscribe to text events, then await the final message.
const stream = client.messages.stream({
model: "claude-opus-5-5",
max_tokens: 64000,
messages: [{ role: "user", content: "Write a story" }],
});
stream.on("text", (text) => process.stdout.write(text));
const message = await stream.finalMessage();