Python / FastAPI Basics Interview Questions
How do you stream large responses in FastAPI using StreamingResponse?
StreamingResponse lets you send data incrementally — essential for large file downloads, CSV exports, real-time data feeds, or AI token streaming — without loading everything into memory first.
from fastapi import FastAPI from fastapi.responses import StreamingResponse import asyncio import csv import io app = FastAPI() # Stream a large CSV without loading it all into memory @app.get("/export/users") async def export_users(): async def generate_csv(): output = io.StringIO() writer = csv.writer(output) writer.writerow(["id", "username", "email"]) # header yield output.getvalue() output.seek(0) output.truncate(0) for i in range(1_000_000): # stream 1M rows writer.writerow([i, f"user{i}", f"user{i}@example.com"]) if i % 1000 == 0: # flush every 1000 rows yield output.getvalue() output.seek(0) output.truncate(0) await asyncio.sleep(0) # yield control to event loop return StreamingResponse( generate_csv(), media_type="text/csv", headers={"Content-Disposition": "attachment; filename=users.csv"}, ) # Server-Sent Events (SSE) for real-time updates @app.get("/events") async def event_stream(): async def generate(): for i in range(10): yield f"data: Event {i}\n\n" # SSE format await asyncio.sleep(1) return StreamingResponse( generate(), media_type="text/event-stream", headers={"Cache-Control": "no-cache"}, ) # Stream a file from disk @app.get("/download/{filename}") async def download_file(filename: str): def iterfile(): with open(f"/data/{filename}", "rb") as f: yield from f # yields chunks as they are read return StreamingResponse(iterfile(), media_type="application/octet-stream")
More Related questions...