Python / FastAPI 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")
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
