StreamingResponse enables streaming large amounts of data or real-time content to clients using generator functions. This is useful for large files, real-time data feeds, or when you want to start sending data before it’s fully available.
Import
Class Signature
Constructor Parameters
Iterable[str] | Iterable[bytes] | AsyncIterable[str] | AsyncIterable[bytes]
required
A generator or async generator that yields chunks of data as strings or bytes.
int
default:"200"
The HTTP status code for the response.
dict | None
default:"None"
Additional HTTP headers to include in the response.
str | None
default:"None"
The media type for the response. Common values include
text/plain, application/octet-stream, etc.BackgroundTask | None
default:"None"
Background task to run after the stream completes.
Usage
Basic Streaming
Stream text data line by line:Streaming Bytes
Stream binary data:Synchronous Generator
Use regular (non-async) generators:Direct StreamingResponse
CreateStreamingResponse directly with a generator:
Streaming with Custom Headers
Streaming Large Files
Stream file contents in chunks:Notes
- Generators can be sync or async - FastAPI handles both
- The generator can yield
strorbytes - String chunks are automatically encoded to UTF-8 bytes
- The response starts sending immediately when the first chunk is yielded
- For file downloads, consider using
FileResponseinstead for better performance - For Server-Sent Events, use
EventSourceResponseinstead
Performance Considerations
- Streaming is ideal for large datasets that don’t fit in memory
- Clients receive data incrementally without waiting for the entire response
- Use appropriate chunk sizes (typically 4KB-64KB for best performance)
- Consider using
FileResponsefor static files instead of streaming manually
Related
- FileResponse - Optimized for serving files
- EventSourceResponse - Server-Sent Events
- JSONResponse - For JSON data