In FastAPI 0.143, what does a path operation send when it uses yield instead of return and sets no response_class?
answer
- one object per line
- not application/json
- the return annotation does the work
- AsyncIterable[Item] or Iterable[Item]
basics
~20 sSince FastAPI 0.134 it streams JSON Lines: each yielded item is serialized to one JSON line and sent as application/jsonl while the function keeps producing. An AsyncIterable[Item] or Iterable[Item] return type validates and filters every item.
solid answer
~40 sFrom FastAPI 0.134 a path operation that `yield`s, with no `response_class`, is streamed as **JSON Lines**: the response carries `Content-Type: application/jsonl` and every yielded item becomes one JSON object followed by a newline, sent as soon as it is produced. If I annotate the return type as `AsyncIterable[LogEntry]` (or `Iterable[LogEntry]` for a plain `def` generator), FastAPI validates each item against that model, drops undeclared fields and serializes it with Pydantic; the schema also appears in OpenAPI as an `itemSchema`. Without an annotation it falls back to `jsonable_encoder`. A `def` generator is advanced in the thread pool, so it does not block the event loop.
code
python · 25 linesfrom collections.abc import AsyncIterable
import anyio
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class LogEntry(BaseModel):
level: str
message: str
RECENT = [
{"level": "INFO", "message": "worker started", "host_secret": "s3cr3t"},
{"level": "WARN", "message": "queue depth 900"},
]
@app.get("/logs/tail")
async def tail_log() -> AsyncIterable[LogEntry]:
for record in RECENT:
await anyio.sleep(0.1) # stands in for waiting on the next log line
yield record # validated and filtered as LogEntrygo deeper
Recall that yield in a FastAPI path operation means a stream: one JSON object per line, application/jsonl, sent as each item is ready.
Explain how the AsyncIterable or Iterable annotation gives each item validation, field filtering and Pydantic serialization, and what changes without it.
Point out that a bad item is found mid-stream, after the 200 is sent, and say where you would validate earlier or emit an error line.
Weigh JSON Lines against Server-Sent Events for a team's streaming endpoints: which clients consume them, how errors are signalled in-band, and what the item schema documents.
## What a yielding path operation is A **path operation function** is the function you decorate with `@app.get(...)`, `@app.post(...)` and so on. Normally it `return`s one value and FastAPI turns it into one JSON document. Since **FastAPI 0.134**, the function may instead contain `yield`, which makes it a **generator function**. FastAPI notices this when the route is registered and, if you did not pass a `response_class`, it serves the route as a **stream of JSON Lines**. **JSON Lines** is a format with one complete JSON value per line, separated by newline characters, instead of a single array wrapped in `[` and `]`. The client can parse line one while the server is still producing line two, which is why it suits a log tail, telemetry, or a model's partial output. ## What goes over the wire For the log-tail endpoint in the example, a request returns status `200` with `Content-Type: application/jsonl`, and the body arrives as: ``` {"level":"INFO","message":"worker started"} {"level":"WARN","message":"queue depth 900"} ``` Each line is written to the connection when its item is yielded, not when the function finishes. Under the hood FastAPI wraps the generator in Starlette's `StreamingResponse` with `media_type="application/jsonl"`, appending `\n` after every serialized item. | What you declare | How each item is turned into a line | |---|---| | `-> AsyncIterable[LogEntry]` on `async def` | validated against `LogEntry`, filtered to its fields, serialized by Pydantic | | `-> Iterable[LogEntry]` on `def` | the same, with the generator advanced in the thread pool | | no return annotation | passed through `jsonable_encoder`, then `json.dumps` | FastAPI recognizes `AsyncIterable`, `AsyncIterator`, `AsyncGenerator`, `Iterable`, `Iterator` and `Generator` as stream annotations and takes their first type argument as the **item type**. ## Validation and filtering per item With an item type declared, FastAPI applies to every single item what it applies to one returned model: - **Validation**: a dict or object is validated against the model; a missing required field raises `ResponseValidationError`. - **Filtering**: fields the model does not declare are dropped. In the example the `host_secret` key never reaches the client. - **Serialization**: Pydantic produces the JSON bytes directly, which the FastAPI docs describe as much faster than the unannotated path. - **Documentation**: the generated OpenAPI response lists `application/jsonl` with the model as its `itemSchema`. - **Response-model options**: `response_model_exclude_unset` and its siblings on the decorator apply to each item. One consequence matters in production: an item that fails validation is discovered only when it is reached. By then the status line and earlier lines have been sent, so the error cannot become a `500` response; the stream is cut instead. ## def or async def generators Both styles work: 1. An `async def` generator is iterated on the event loop. Anything slow inside it must be awaited, or it stalls every other request. 2. A plain `def` generator is advanced one step at a time in a worker thread, so a blocking read inside it does not stop the loop. Annotate it with `Iterable[...]`, not `AsyncIterable[...]`. How the thread pool itself is sized and shared is covered with FastAPI's thread-pool offloading. ## Status, headers and background tasks A streamed response still goes through the rest of FastAPI's machinery: - The status is `200` unless the decorator sets `status_code`, or a dependency sets it on a `Response` parameter; both are read when the stream is built, before the generator runs. - Headers set on a `Response` parameter by a dependency are merged into the streamed response. - Tasks added to `BackgroundTasks` run after the last line has been sent, not when the function is called. ## Things that are easy to get wrong - Expecting `application/json` and a JSON array: a client that calls a whole-body JSON parser on the response will fail on the second line. - Annotating an `async def` generator with `list[LogEntry]`: that is not a stream type, so FastAPI finds no item type and sends every item unvalidated and unfiltered through `jsonable_encoder`. - Assuming the old recipe is still required: wrapping a generator in `StreamingResponse(...)` by hand still works, but it skips per-item validation and sends whatever bytes or strings you produce. - Forgetting that `response_class` changes the mode: with `EventSourceResponse` the same `yield` produces Server-Sent Events, and with `StreamingResponse` it produces raw chunks.
- What does FastAPI do with a yielded dict when the generator has no return annotation?It runs the item through `jsonable_encoder` and `json.dumps`, then writes it as one line. Nothing is validated or filtered, so every key in the dict is sent, and the OpenAPI entry has no item schema to show clients.
- How would you make the same generator stream raw text instead of JSON Lines?Set `response_class=StreamingResponse` (or a subclass with a `media_type`). FastAPI then hands each chunk to the response as it is: strings are encoded to bytes, bytes pass through, and the annotation is ignored for validation.
- A yielding path operation returns one JSON array once the generator finishes.
- Streaming in FastAPI always requires returning a StreamingResponse yourself.
- With no response_class, a generator endpoint's return annotation is only an editor hint.
- A def generator endpoint blocks the event loop while it waits for data.
- Yielded items are sent with Content-Type application/json.
Assumes FastAPI 0.143; yield path operations stream JSON Lines since 0.134, and before that a generator had to be wrapped in StreamingResponse by hand.