← All notes

Stream a FastAPI response with StreamingResponse and a generator

Answer: StreamingResponse takes an async generator or a normal generator/iterator and streams the response body. FileResponse asynchronously streams a file as the response.

StreamingResponse

Pass a function that uses yield, or any iterator, to StreamingResponse. Starlette also sets media_type on that response. File-like objects created by open() are normal iterators, so you can return them directly in a StreamingResponse.

Cancellation of an async task happens at an await. Without that point, the generator can not be cancelled properly and may keep running after cancellation is requested. The FastAPI example adds await anyio.sleep(0) so the event loop can handle cancellation, which matters more for large or infinite streams. A Stream Data style can handle cancellation behind the scenes.

FileResponse

FileResponse takes a different set of arguments: path (the file path to the file to stream), headers, media_type (inferred from the filename or path if unset), and filename (included in Content-Disposition when set). File responses will include appropriate Content-Length and Last-Modified headers.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: FastAPI docs, Custom Response - HTML, Stream, File, others; Starlette docs, Responses. MIT; BSD-3-Clause. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: FastAPI docs, Custom Response - HTML, Stream, File, others; Starlette docs, Responses. MIT; BSD-3-Clause.

Cite this

Permanent ID: iil:note:wpfktxgm

iinventedlight. 2026. "Stream a FastAPI response with StreamingResponse and a generator." iinventedlight Library, iil:note:wpfktxgm, version of 2026-11-19. https://iinventedlight.com/library/notes/fastapi-streaming-responses/. License: CC-BY-4.0.

@misc{iil_note_wpfktxgm,
  author = {{iinventedlight}},
  title = {{Stream a FastAPI response with StreamingResponse and a generator}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-19},
  url = {https://iinventedlight.com/library/notes/fastapi-streaming-responses/},
  note = {Permanent ID iil:note:wpfktxgm. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/fastapi-streaming-responses.md.