Sub topic 4
Returning a generator with StreamingResponse
This chapter covers how FastAPI turns an async generator into a streamed HTTP response. It assumes you know basic Python including async/await, how HTTP requests and responses work, and how to write a FastAPI route with a Pydantic model. It also assumes you have read the previous chapter on async generators. Server-Sent Events formatting, the LLM client, and error handling come in later chapters.
What StreamingResponse does
A normal FastAPI route returns a value. FastAPI serializes it to JSON, computes a Content-Length, and sends the whole body at once. The client sees nothing until the handler has finished.
StreamingResponse changes the last step. You give it an iterator, and it sends each item to the client as a separate piece of the body. The handler returns as soon as it has built the response object. The generator then runs while the server is writing the response.
StreamingResponse comes from Starlette, the framework FastAPI is built on. FastAPI re-exports it:
from fastapi.responses import StreamingResponseIts main constructor arguments are:
| Argument | Meaning |
|---|---|
| `content` | A sync or async iterable that yields `str` or `bytes`. |
| `status_code` | The HTTP status, `200` by default. |
| `headers` | A dict of extra response headers. |
| `media_type` | The value of the `Content-Type` header. |
| `background` | A background task to run after the response is sent. |
A first streaming endpoint
This example yields a chunk every half second. The client receives each chunk as it is produced, so the full response takes about two and a half seconds but the first bytes arrive almost at once.
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def count():
for i in range(5):
yield f"chunk {i}\n"
await asyncio.sleep(0.5)
@app.get("/count")
async def stream_count():
return StreamingResponse(count(), media_type="text/plain")Save this as main.py and run it with uvicorn main:app. Then watch the output arrive with curl. The -N flag turns off curl's own output buffering, so you see chunks as they come in:
import subprocess
subprocess.run(["curl", "-N", "http://localhost:8000/count"], check=True)You can also run curl -N http://localhost:8000/count directly in a terminal. If the lines appear one at a time, streaming works. If all five lines appear together after a delay, something between the generator and the client is buffering. The chapter on proxy buffering covers that case.
What happens on the wire
The sequence of events is worth understanding, because most streaming bugs come from a wrong picture of it.
Three details follow from this sequence.
- The status code and headers are sent before the generator produces its first item. Once they are on the wire, you cannot change them. A failure inside the generator can no longer become a
500response. This is why a later chapter treats errors after the response has started as their own topic. - There is no
Content-Length. The server does not know the final size, so with HTTP/1.1 it usesTransfer-Encoding: chunked. Each piece is prefixed with its length and the body ends with a zero-length chunk. With HTTP/2 the framing is different, but the idea is the same. - The generator is pulled, not pushed.
StreamingResponseasks for the next item only after it has handed the previous one to the server. A slow client that is not reading will slow the loop down, and that is a form of backpressure.
Sync and async iterables
StreamingResponse accepts both kinds of iterable. The difference matters for the event loop.
- An async generator is iterated directly on the event loop. Each
awaitinside it lets other requests run. - A sync generator is iterated in a worker thread pool by Starlette, using
iterate_in_threadpool. This keeps blocking code from freezing the loop, but every item costs a thread hop.
For an LLM endpoint, use an async generator with an async client. Using a sync generator with time.sleep or a blocking HTTP call is the usual way to stall a server by accident. If you put blocking code directly inside an async def generator, it blocks the whole event loop, and every other request waits.
import time
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
def slow_sync():
for i in range(3):
time.sleep(1) # fine here: runs in a worker thread
yield f"item {i}\n"
@app.get("/sync")
def stream_sync():
return StreamingResponse(slow_sync(), media_type="text/plain")The sync version above is safe because Starlette moves it off the loop. The same time.sleep(1) inside an async def generator would not be safe.
Content types and what you can yield
The generator may yield str or bytes. Strings are encoded as UTF-8 before they are written. Other types, such as dict or int, raise an error when the response tries to encode them. If you want to stream JSON objects, serialize each one yourself.
The media_type argument sets Content-Type, and it tells the client how to interpret the stream. Common choices:
| `media_type` | Use |
|---|---|
| `text/plain` | Raw text, such as the demo above. |
| `application/x-ndjson` | One JSON object per line. |
| `text/event-stream` | Server-Sent Events, which browsers read with `EventSource`. |
For text types, Starlette appends ; charset=utf-8 to the header. The next chapter uses text/event-stream and shows the message format that goes with it.
Here is a generator that streams newline-delimited JSON:
import asyncio
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def records():
for i in range(3):
yield json.dumps({"index": i}) + "\n"
await asyncio.sleep(0.2)
@app.get("/records")
async def stream_records():
return StreamingResponse(records(), media_type="application/x-ndjson")Chunk boundaries are not message boundaries
Each yield usually becomes one write on the server, but the client does not receive that structure. TCP, proxies, and client libraries may split one yielded item into several reads, or merge several items into one. A client that assumes "one read equals one yield" will eventually break.
This is the reason streamed formats carry their own delimiters. NDJSON uses newlines. SSE uses a blank line between events. A client should accumulate bytes and split on the delimiter, not on read boundaries. Line-oriented helpers such as httpx's aiter_lines() do this for you.
Where the generator runs
A common mistake is to think that the route function runs the generator. It does not. The route builds the generator object, which does no work yet, and returns the response. The server then drives the generator after the route has already returned.
Two consequences follow.
- Dependencies are not kept alive by the route's scope in the way you might expect. In current FastAPI versions, a dependency with
yieldhas its exit code run after the response is finished, but the exact timing has changed between releases. Do not rely on a yield-dependency's cleanup running while your generator is still using the resource. Prefer a shared client that lives for the whole application, such as a cached client returned from a plain dependency. - Exceptions raised inside the generator do not reach your route's
try/except. Atryblock aroundreturn StreamingResponse(...)only catches errors from building the response. Put error handling inside the generator itself.
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def failing():
yield "start\n"
await asyncio.sleep(0.1)
raise RuntimeError("boom")
@app.get("/fail")
async def fail():
try:
return StreamingResponse(failing(), media_type="text/plain")
except RuntimeError:
# Never reached: the generator has not run yet.
return StreamingResponse(iter(["handled\n"]))Run this and call curl -N -i http://localhost:8000/fail. The client gets 200 OK and start, and then the connection ends abnormally while the server logs a traceback. The except branch never runs.
Common mistakes
- Awaiting the whole result first. Writing
text = await collect_everything()and then yielding it in a loop adds no streaming benefit. The first byte must be produced before the slow work finishes. - Returning the generator function instead of the generator.
StreamingResponse(count)passes a function, not an iterable. Call it:StreamingResponse(count()). - Yielding a non-string value. Yield
strorbytesonly. - Blocking the event loop. Use async libraries, such as
httpx.AsyncClientorAsyncOpenAI, inside async generators. - Using
response_modeland expecting validation. FastAPI does not validate or serialize the stream's contents. The stream is passed through as it is. - Assuming the stream is not buffered downstream. A reverse proxy, a gzip middleware, or a CDN can hold output until it has a full buffer. The generator being correct does not prove the client sees tokens promptly.
Summary of the model
You now have the working model for the rest of the tutorial.
- The route returns immediately with a
StreamingResponsethat wraps a generator. - The server sends the status and headers, then pulls items from the generator one at a time.
- Each item is written to the client as a chunk. The body has no declared length.
- The generator, not the route, owns the work, the errors, and the cleanup.
The next chapter gives the chunks a structure, so that a client can tell tokens, completion, and errors apart.
Exercise
A route builds StreamingResponse(gen(), media_type="text/plain"), and gen() raises an exception after yielding its second item. The route is wrapped in try/except Exception that returns a JSON error with status 500. What does the client observe, and why does the except block not help?
Show answer
The client receives a 200 status and the first two items, then the connection ends abnormally (an incomplete chunked body). The route function returned the response object before the generator ran, so the exception is raised later, while the server is writing the body. The status and headers were already sent, so they cannot be replaced, and the route's try/except is no longer on the call stack. The generator must catch its own exceptions and report the error inside the stream.
Exercise
You write StreamingResponse(count, media_type="text/plain") where count is the async generator function from the first example. What goes wrong, and what is the fix?
Show answer
count is a function, not an iterable of chunks. Starlette expects an object it can iterate over, so the response fails when it tries to iterate. The fix is to call the function so the response receives the async generator object: StreamingResponse(count(), media_type="text/plain").
Exercise
Why does a curl run show all five chunk lines at once after a delay when you forget -N, even though the server streams correctly? Name one other component that could cause the same symptom.
Show answer
Without -N, curl buffers its own output and prints it in larger blocks, so the stream looks unstreamed even though the chunks arrived separately. A reverse proxy such as nginx, a compression middleware, or a CDN can cause the same symptom by buffering the response before forwarding it.