Trung BìnhFastAPI iconFastAPI

StreamingResponse và FileResponse dùng khi nào?

StreamingResponse dùng khi response lớn hoặc sinh dần như export CSV, proxy stream, AI token stream. FileResponse dùng trả file có sẵn trên disk và xử lý headers phù hợp.

Ví dụ streaming:

python
async def rows():
    for row in data:
        yield json.dumps(row) + "\n"

return StreamingResponse(rows(), media_type="application/x-ndjson")

Cần chú ý client disconnect, timeout, backpressure và không giữ toàn bộ payload lớn trong memory.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI