Sub topic 4
Returning a generator with StreamingResponse
This chapter assumes you can write a basic FastAPI route, you know Python async/await, and you have seen an async generator (a function with async def that uses yield). Here you will connect the two: FastAPI sends whatever the generator yields, one piece at a time.
What StreamingResponse does
A normal FastAPI return value is serialized and sent once the handler finishes. StreamingResponse takes an iterable instead. It sends the response headers, then writes each item the iterable produces to the connection as soon as the item is available.
The iterable can be a regular generator, an async generator, or any object that supports iteration. For LLM work you will almost always pass an async generator, because waiting on the model must not block the event loop.
A first working example
This endpoint yields a line every half second.
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 it as main.py and run uvicorn main:app. Then call it with curl, using -N to turn off curl's own output buffering:
curl -N http://localhost:8000/countYou should see a new line appear every half second, not all five at once after 2.5 seconds.
How the pieces fit
Key points about this flow:
- The handler returns quickly. The generator body runs afterward, while the server is already sending the response.
- The status code and headers are sent before the first chunk. After that, you can no longer change them.
- Each
yieldhands one chunk to the server. The chunk is astrorbytes. Strings are encoded as UTF-8.
The media_type argument
media_type sets the Content-Type header. It tells the client how to interpret the bytes.
| Value | Use it for |
|---|---|
| `text/plain` | Raw text chunks, as in the example above |
| `text/event-stream` | Server-Sent Events, covered in the next chapter |
| `application/x-ndjson` | One JSON object per line |
Pick the type that matches the framing you actually write. A mismatch confuses clients, because browsers and SSE libraries decide how to parse the body from this header.
Common errors
- Passing a list or finished result. If you build the full text first and wrap it in
StreamingResponse, the client still waits for everything. Streaming only helps if the generator produces items as the work happens. - Blocking calls inside the generator. A call like
time.sleep(0.5)or a synchronous HTTP request freezes the event loop, which stalls every other request. Useawait asyncio.sleepand async clients. - Forgetting to call the generator function. Write
StreamingResponse(count(), ...), notStreamingResponse(count, ...). The first passes a generator object. The second passes a function, which is not iterable. - Raising an exception for the status code. Once streaming has begun, the 200 status is already sent. A later exception cannot turn it into a 500. A later chapter covers how to report such errors.
Exercise
Exercise
A teammate writes an endpoint that loops over five LLM chunks, appends each to a string, and then returns StreamingResponse(iter([fulltext]), mediatype="text/plain"). The client sees no output until all chunks arrive. Why, and what should change?
Show answer
The loop finishes before the response object is created, so the whole text exists before anything is sent, and the iterable holds just one item. Move the loop into an async generator that yields each chunk as it arrives, and pass that generator to StreamingResponse.
Exercise
Why must a call to time.sleep(0.5) inside the generator be replaced with await asyncio.sleep(0.5)?
Show answer
time.sleep blocks the whole event loop, so no other request can be served during the pause. await asyncio.sleep suspends only this generator and lets the loop run other work.