fix: resolve ForwardRef in Annotated types for OpenAPI schema generation by BillionClaw · Pull Request #15131 · fastapi/fastapi
Description
Fixes #13056
When using from __future__ import annotations with Annotated[Type, Depends(...)] where Type is defined after the route function, the OpenAPI schema generation would fail with a PydanticUserError about unresolved ForwardRefs.
Changes
Modified ModelField in fastapi/_compat/v2.py to:
- Add a
core_schemaproperty that checks if the schema contains unresolved ForwardRefs - If unresolved, rebuild the TypeAdapter with a combined namespace from all loaded modules
- Updated
get_definitions()and_has_computed_fields()to use the new property
Testing
Tested with the reproduction case from the issue. The OpenAPI schema is now generated correctly with the referenced type schema properly defined.