← All notes

Stream a response body from Starlette or FastAPI

Answer: StreamingResponse takes an async generator or a normal generator or iterator and streams the response body. Starlette and FastAPI both ship that class.

Starlette

Pass the generator and a media_type such as text/html. The slow_numbers example yields HTML incrementally and uses asyncio.sleep. File-like objects (like those created by open()) are normal iterators. Those objects can be returned directly in a StreamingResponse. FileResponse streams a file asynchronously. It also supports HTTP range requests.

FastAPI

The FastAPI example is a function with yield. An async task can only be cancelled when it reaches an await. Without that, the generator may keep running after cancellation is requested. The example adds await anyio.sleep(0) so the event loop has a chance to halt the generator.

| StreamingResponse | FileResponse | |---|---| | StreamingResponse | Streams a generator or iterator as the body | | media_type | Argument such as text/html | | FileResponse | Asynchronously streams a file as the response | | await | Needed so an async generator can be cancelled |

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: Starlette, Responses; FastAPI, Custom Response - HTML, Stream, File, others. BSD-3-Clause; MIT. Text was condensed and changed from the originals.

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

Cite this

Permanent ID: iil:note:xnkhqjsh

iinventedlight. 2026. "Stream a response body from Starlette or FastAPI." iinventedlight Library, iil:note:xnkhqjsh, version of 2026-11-19. https://iinventedlight.com/library/notes/starlette-streaming-responses/. License: CC-BY-4.0.

@misc{iil_note_xnkhqjsh,
  author = {{iinventedlight}},
  title = {{Stream a response body from Starlette or FastAPI}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-19},
  url = {https://iinventedlight.com/library/notes/starlette-streaming-responses/},
  note = {Permanent ID iil:note:xnkhqjsh. 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).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

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