Repository navigation
Annotated[AsyncIterator[T], ...] return annotations fail route registration #16337
Replies: 7 comments 2 replies
|
"Great catch on this routing registration edge case with Annotated and AsyncIterator. As you pointed out, when Pydantic/FastAPI evaluates the inner metadata unwrapping during route compilation under Python 3.13, the generator type structure can break route registration if not properly peeled before flow origin detection. Your proposed fix to unwrap Annotated recursively in functions like get_stream_item_type() makes complete sense to ensure seamless compatibility." |
Root Cause AnalysisTracing the route compilation flow during
Minimal & Robust Solution
def get_stream_item_type(annotation: Any) -> Any | None:
while get_origin(annotation) is Annotated:
type_args = get_args(annotation)
if not type_args:
break
annotation = type_args[0]
origin = get_origin(annotation)
if origin is not None and origin in _STREAM_ORIGINS:
type_args = get_args(annotation)
if type_args:
return type_args[0]
return Any
return NoneVerification & InvariantsTesting against current
We have this verified locally along with unit tests. If maintainers would like a PR submitted for this per repository guidelines, happy to open one! |
|
I'm not sure if it is necessarily a bug. The FastAPI documentation suggests us to not use the annotation in the return because FastAPI won't handle it. They say that we should use it only for typing and editor tools. However, at the same time, I was able to make your code run by adding the I'm not sure if it is a bug, or just a matter of adding this detail in the documentation. |
|
@VictorOF That's a great point regarding Modern Streaming ArchitectureIn recent releases, FastAPI added native streaming support for JSON Lines and Server-Sent Events (see Streaming JSON Lines). Under this design:
Why
|
|
That's a great test case, @VictorOF! Looking at the generated OpenAPI schema actually reveals the subtle trade-off here: 1. Why
|
|
Hi everyone, I investigated this route registration failure, developed the focused fix, and verified it against the full test suite. Root CauseIn When an endpoint returns SolutionUnwrap def get_stream_item_type(annotation: Any) -> Any | None:
while get_origin(annotation) is Annotated:
type_args = get_args(annotation)
if not type_args:
break
annotation = type_args[0]
origin = get_origin(annotation)
if origin is not None and origin in _STREAM_ORIGINS:
type_args = get_args(annotation)
if type_args:
return type_args[0]
return Any
return None |
|
Yes, I think that's correct. Annotated[Annotated[AsyncGenerator[str, None], "inner"], "outer"]is represented as a single So for That would make the change a bit simpler while still handling both: Annotated[AsyncIterator[int], "metadata"]
Annotated[AsyncGenerator[str, None], "metadata"]The useful regression test here would therefore be the single |

Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Annotated[AsyncIterator[T], ...]return annotations fail route registrationSummary
On FastAPI revision
50113da16fec53b66b80d75e80a89296de4fa5a5, wrapping anasync-stream return annotation in
typing.Annotatedcauses route registrationto raise
FastAPIError, while the equivalent unwrapped annotation registerssuccessfully.
This is distinct from the
APIRouter.include_routerpropagation issue in#15401: the failure happens while the route is first constructed, even when it
is declared directly on
FastAPI.Reproduction
The reproduction was run against the current checkout with the same result
for
typing.AsyncIteratorandcollections.abc.AsyncIterator.Actual behavior
get_stream_item_type()checks only whether the outerget_origin(annotation)is one of the supported stream origins. For an
Annotatedreturn annotation,the outer origin is
Annotated, so the helper returnsNone. The completeAnnotated[AsyncIterator[int], ...]object is then treated as a response modeland route construction fails before the application can start.
Relevant code:
fastapi/dependencies/utils.py:261-268,get_stream_item_type()fastapi/routing.py:1086-1087, where the helper is calledExpected behavior
Annotated[AsyncIterator[int], metadata]should be accepted wherever theequivalent
AsyncIterator[int]annotation is accepted. The metadata should bepreserved or ignored according to FastAPI's existing
Annotatedconventions,and the stream item type should resolve to
int.Impact
Applications using metadata-bearing return annotations cannot start. This is a
compatibility failure for valid PEP 593 typing syntax and affects deployment
before the first request. It also prevents the framework from generating the
intended stream item schema.
Suggested fix
Unwrap
Annotatedbefore stream-origin detection (or recurse through it insideget_stream_item_type()), matching the existing annotation-unwrapping logicused for parameters. Add regression coverage for
Annotated[AsyncIterator[T], ...]andAnnotated[AsyncGenerator[T, None], ...]return annotations.Environment
50113da16fec53b66b80d75e80a89296de4fa5a5Duplicate check
stream_item_typenot propagated throughAPIRouter+include_router#15401 concernsAPIRouter.include_routerlosingstream_item_typeafter a route was already constructed; this reproduction fails during direct route registration and does not require a router merge.get_stream_item_type()logic infastapi/dependencies/utils.py, so the finding remains independently reproducible against the reviewed revision.All reactions