Skip to main content
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

Create StreamingResponse 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 str or bytes
  • 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 FileResponse instead for better performance
  • For Server-Sent Events, use EventSourceResponse instead

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 FileResponse for static files instead of streaming manually