Basic Streaming
Create a streaming endpoint usingStreamingResponse 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:Custom Media Types
Create custom streaming response classes with specific media types:Synchronous Generators
Use regular (non-async) generator functions:Generator Without Type Annotations
You can omit type annotations if needed:StreamingResponse Constructor
CreateStreamingResponse instances directly:
Streaming with yield from
Useyield 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
EventSourceResponseinstead) - Reducing time to first byte (TTFB) for large responses
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