Repository navigation
Description
Summary
When an SSE route (response_class=EventSourceResponse + AsyncIterator[Frame] return annotation) is defined on an APIRouter and then merged onto a FastAPI app via include_router, the resulting merged route loses its stream_item_type. As a consequence, the OpenAPI text/event-stream response schema omits the data.contentSchema, so tooling like datamodel-codegen cannot generate frame models.
Defining the same route directly on the FastAPI app via @app.post(...) works correctly.
Reproduction
from collections.abc import AsyncIterator
from fastapi import APIRouter, FastAPI
from fastapi.sse import EventSourceResponse
from pydantic import BaseModel
class Frame(BaseModel):
kind: str
# Case A — route registered directly on the app: works
app_a = FastAPI()
@app_a.post("/s", response_class=EventSourceResponse)
async def a() -> AsyncIterator[Frame]:
yield Frame(kind="x")
# Case B — route defined on a router, then `include_router`: broken
router = APIRouter()
@router.post("/s", response_class=EventSourceResponse)
async def b() -> AsyncIterator[Frame]:
yield Frame(kind="x")
app_b = FastAPI()
app_b.include_router(router)
print("DIRECT:", app_a.routes[-1].stream_item_type)
print("ROUTER (pre-include):", router.routes[-1].stream_item_type)
print("APP (post-include):", app_b.routes[-1].stream_item_type)
def has_content_schema(spec: dict) -> bool:
sse = spec["paths"]["/s"]["post"]["responses"]["200"]["content"]["text/event-stream"]
return "contentSchema" in sse.get("itemSchema", {}).get("properties", {}).get("data", {})
print("DIRECT openapi has contentSchema:", has_content_schema(app_a.openapi()))
print("INCLUDE_ROUTER openapi has contentSchema:", has_content_schema(app_b.openapi()))Output:
DIRECT: <class '__main__.Frame'>
ROUTER (pre-include): <class '__main__.Frame'>
APP (post-include): None
DIRECT openapi has contentSchema: True
INCLUDE_ROUTER openapi has contentSchema: False
Expected
After include_router, the merged route on app_b should carry the same stream_item_type as the source route, and the emitted OpenAPI should include the contentSchema under responses.200.content["text/event-stream"].itemSchema.properties.data referencing Frame.
Actual
The merged route's stream_item_type is None; the emitted OpenAPI shows the generic SSE envelope (data: string, event, id, retry) with no contentSchema.
Root cause (proposed)
In fastapi/routing.py, APIRoute.__init__ populates self.stream_item_type only inside the branch guarded by isinstance(response_model, DefaultPlaceholder):
if isinstance(response_model, DefaultPlaceholder):
return_annotation = get_typed_return_annotation(endpoint)
if lenient_issubclass(return_annotation, Response):
response_model = None
else:
stream_item = get_stream_item_type(return_annotation)
if stream_item is not None:
if (
isinstance(response_class, DefaultPlaceholder)
or lenient_issubclass(response_class, EventSourceResponse)
) and not lenient_issubclass(stream_item, ServerSentEvent):
self.stream_item_type = stream_item
response_model = None
else:
response_model = return_annotation
self.response_model = response_modelWhen the source route (on the APIRouter) is created, response_model starts as a DefaultPlaceholder, the detection runs, and self.response_model is overwritten to None.
APIRouter.include_router then creates the merged route with:
self.add_api_route(
prefix + route.path,
route.endpoint,
response_model=route.response_model, # now None, not DefaultPlaceholder
...
response_class=use_response_class,
...
)On the merged route's __init__, isinstance(response_model, DefaultPlaceholder) is now False, so the detection branch is skipped and self.stream_item_type stays at its initial None.
The symmetric issue likely affects JSONL streaming (response_class=DefaultPlaceholder path) too, since it's gated by the same DefaultPlaceholder check on response_model.
Suggested fix
Either:
- In
include_router, additionally copystream_item_typeonto the new route (simplest, closest to the current wiring). - In
APIRoute.__init__, run stream-item detection regardless of whetherresponse_modelis aDefaultPlaceholder, as long asresponse_model is Noneafter the conditional.
Environment
fastapi==0.135.2pydantic==2.12.5starlette==1.0.0- Python
3.11.6 - macOS 14.4.1
Happy to open a PR if the preferred fix direction is specified.
Activity
FrimpsManu commentedon Apr 22, 2026
Hi, I’d like to work on this issue if it is still available.
YuriiMotov commentedon Apr 22, 2026
As you can see there is a PR linked to the issue. You can review it
Fix SSE stream_item_type lost through include_router (fastapi#15401)
shalom-ezekiel commentedon Apr 26, 2026
Fix SSE stream_item_type lost through include_router (fastapi#15401)
devloperdevesh commentedon May 8, 2026
I investigated the issue locally and was able to reproduce the
stream_item_typepropagation problem throughinclude_router().I’d like to work on a fix and add regression tests for the SSE/OpenAPI behavior if no one else is currently handling it.
BoozeLee commentedon May 10, 2026
bernatGene commentedon May 12, 2026
facing this issue on my project.
tiangolo commentedon May 18, 2026
We'll continue tracking this internally, I'll close this one to prevent more automated AI generated PRs that only add to our overhead. ☕
https://fastapi.tiangolo.com/contributing/#automated-code-and-ai