Skip to main content
Streaming responses allow you to send data to clients incrementally, which is ideal for large files, generated content, or any scenario where you want to start sending data before the entire response is ready.

Basic Streaming

Create a streaming endpoint using StreamingResponse and a generator function:
The generator function can be either async (using async def and yield) or synchronous (using regular def and yield).

Streaming Text

Stream text content line by line:

Streaming Bytes

Stream binary data:
StreamingResponse accepts both str and bytes iterators. String content is automatically encoded as UTF-8.

Streaming Files

Stream large files efficiently:
For static file serving, consider using FileResponse instead, which handles range requests and caching automatically.

Custom Media Types

Create custom streaming response classes with specific media types:

Synchronous Generators

Use regular (non-async) generator functions:
Synchronous generators block the event loop. Use async generators for I/O-bound operations to maintain high concurrency.

Generator Without Type Annotations

You can omit type annotations if needed:

StreamingResponse Constructor

Create StreamingResponse instances directly:

Streaming with yield from

Use yield from to delegate to another generator:

Streaming JSON Lines

Stream JSON objects one per line (JSONL format):
The application/x-ndjson media type indicates newline-delimited JSON, also known as JSON Lines or JSONL.

Streaming with Database Queries

Stream database results efficiently:

Progress Updates

Stream progress updates for long-running operations:

Custom Headers and Status Codes

Set custom headers and status codes:

Background Processing

Combine streaming with background tasks:
Background tasks run after the response is sent to the client, making them perfect for cleanup operations.

Testing Streaming Endpoints

Test streaming responses using FastAPI’s test client:

When to Use Streaming

Use streaming responses when:
  • Sending large files that don’t fit in memory
  • Generating content dynamically (e.g., reports, exports)
  • Streaming database query results
  • Providing real-time progress updates
  • Implementing Server-Sent Events (use EventSourceResponse instead)
  • Reducing time to first byte (TTFB) for large responses
Once streaming starts, you cannot modify headers or status codes. Set all headers before returning the StreamingResponse.

Performance Considerations

  • Chunk size: Balance between memory usage and network overhead (8KB-64KB is typical)
  • Async vs sync: Use async generators for I/O-bound operations
  • Buffering: Clients may buffer chunks, affecting perceived streaming
  • Error handling: Errors during streaming may result in partial responses
For static files, use FileResponse instead of StreamingResponse. It provides better performance with automatic support for range requests, caching, and efficient file serving.