Skip to content

SSE stream_item_type not propagated through APIRouter + include_router #15401

Closed

Description

@tikal

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_model

When 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:

  1. In include_router, additionally copy stream_item_type onto the new route (simplest, closest to the current wiring).
  2. In APIRoute.__init__, run stream-item detection regardless of whether response_model is a DefaultPlaceholder, as long as response_model is None after the conditional.

Environment

  • fastapi==0.135.2
  • pydantic==2.12.5
  • starlette==1.0.0
  • Python 3.11.6
  • macOS 14.4.1

Happy to open a PR if the preferred fix direction is specified.

Activity

  1. FrimpsManu commented on Apr 22, 2026

    @FrimpsManu

    Hi, I’d like to work on this issue if it is still available.

  2. YuriiMotov commented on Apr 22, 2026

    @YuriiMotov
    Member

    Hi, I’d like to work on this issue if it is still available.

    As you can see there is a PR linked to the issue. You can review it

  3. shalom-ezekiel commented on Apr 26, 2026

    @shalom-ezekiel
  4. devloperdevesh commented on May 8, 2026

    @devloperdevesh

    I investigated the issue locally and was able to reproduce the stream_item_type propagation problem through include_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.

  5. BoozeLee commented on May 10, 2026

    @BoozeLee
  6. bernatGene commented on May 12, 2026

    @bernatGene

    facing this issue on my project.

  7. tiangolo commented on May 18, 2026

    @tiangolo
    Member

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions