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:

  1. Add a core_schema property that checks if the schema contains unresolved ForwardRefs
  2. If unresolved, rebuild the TypeAdapter with a combined namespace from all loaded modules
  3. 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.