FastAPI by Example: Streaming Response Output
For large datasets or continuous data streams, you don't want to wait for the entire response to be ready. This code example demonstrates how to use `StreamingResponse` to send data chunk by chunk.
Code
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import time
app = FastAPI()
async def fake_video_streamer():
for i in range(10):
yield f"Frame {i}\n"
time.sleep(0.5)
@app.get("/stream")
async def main():
return StreamingResponse(fake_video_streamer())
@app.get("/csv")
async def get_csv():
def iter_csv():
yield "id,name\n"
for i in range(100):
yield f"{i},Item {i}\n"
return StreamingResponse(
iter_csv(),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=data.csv"}
)Explanation
StreamingResponse is a powerful tool in FastAPI that allows you to send data to the client incrementally, rather than waiting for the entire response to be generated. It accepts a Python generator (either synchronous or asynchronous) and iterates over it, sending each yielded chunk to the client immediately. This architecture is essential for high-performance applications that need to handle large datasets or real-time data feeds.
The primary benefit of streaming is memory efficiency. If you were to generate a massive CSV report containing millions of rows, building the entire string in memory before sending it could easily exhaust your server's RAM. By using a generator and StreamingResponse, you only keep a single row (or a small batch of rows) in memory at any given time, allowing you to process virtually infinite datasets with minimal resources.
Beyond file downloads, streaming is the foundation for real-time protocols like Server-Sent Events (SSE). By keeping the connection open and yielding data over an extended period, you can push live updates to the client, such as stock tickers, progress bars, or chat messages. FastAPI handles the underlying network socket management, ensuring that the connection remains stable while your generator produces data.
Code Breakdown
fake_video_streamer is an asynchronous generator. The yield keyword pauses execution and sends the value to the client.StreamingResponse(...) takes the generator as its first argument. It starts iterating immediately upon returning the response.iter_csv is a standard synchronous generator. FastAPI runs synchronous generators in a separate thread to avoid blocking the loop.media_type="text/csv" informs the browser that the incoming stream is a CSV file, often triggering a spreadsheet application to open.
