Repository navigation
Conversation
|
Hi @Anurag-M1, great PR! Supporting One quick observation in while get_origin(annotation) is Annotated:
annotation = get_args(annotation)[0] |
|
Hi @VimalN2005, thanks for reviewing! It looks like your comment may have been submitted before you finished typing. In case you were wondering about the direct
I have also updated the PR description snippet to match the implementation in |
|
Hi @Shriprasad-P, thanks for the review! Yes, the new path is fully covered across unit, end-to-end runtime, and OpenAPI schema generation in
All 8 tests fail on Please let me know if there are any specific scenarios or edge cases you'd like to see added! |
Pull Request
Discussion: #16337
Description
Fixes #16334
Problem
Wrapping an async stream return annotation (e.g.
AsyncIterator[T],AsyncIterable[T], orAsyncGenerator[T, None]) intyping.Annotatedcauses route registration to raiseFastAPIError: Invalid args for response field!at application startup:This occurs because
get_stream_item_type()infastapi/dependencies/utils.pychecks whetherget_origin(annotation)is in_STREAM_ORIGINS. Because the outermost origin ofAnnotated[...]isAnnotated,get_stream_item_typereturnsNone. FastAPI then erroneously falls back to treating the entire streaming iterator annotation as a single HTTP response model, which Pydantic cannot serialize as a field.Solution
Unwrap
Annotatedlayers inget_stream_item_typebefore evaluating against_STREAM_ORIGINS:This restores complete parity between unwrapped
AsyncIterator[T]andAnnotated[AsyncIterator[T], ...]:T.itemSchemafor bothapplication/jsonlandtext/event-stream(SSE).Tests
Added comprehensive test coverage in
tests/test_stream_annotated.py:test_get_stream_item_type_unwraps_annotated: Unit tests verifyingget_stream_item_typeunwrap behavior with single and nestedAnnotatedtypes, sync/async iterators, and non-stream types.test_stream_annotated_jsonl: End-to-end JSON Lines streaming withAnnotated[AsyncIterator[Item], "metadata"].test_stream_nested_annotated_jsonl: NestedAnnotatedwrappers.test_stream_annotated_async_generator:AsyncGenerator.test_stream_annotated_sync: SynchronousIterator.test_stream_annotated_sse: Server-Sent Events withEventSourceResponse.test_router_stream_annotated: Streaming route included throughAPIRouter.test_stream_annotated_openapi_schema: Verifying generated OpenAPIitemSchemafor JSONL and SSE endpoints.All 8 new tests fail on
masterwithFastAPIErrorand pass cleanly with this fix. The existing stream and SSE test suites (67 tests) pass without regression, and allprekpre-commit hooks pass.AI Disclaimer
Prompt: Diagnose issue #16334 / discussion #16337 in FastAPI regarding Annotated stream return annotations, implement the fix in get_stream_item_type, add comprehensive tests, and ensure all tests and linters pass.
Model: Gemini 3.8 Flash
Checklist