diff --git a/fastapi/_compat.py b/fastapi/_compat.py index c07e4a3b0..285327816 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -56,6 +56,9 @@ if PYDANTIC_V2: ) from pydantic._internal._typing_extra import eval_type_lenient from pydantic._internal._utils import lenient_issubclass as lenient_issubclass + from pydantic.errors import ( + PydanticUndefinedAnnotation as PydanticUndefinedAnnotation, + ) from pydantic.fields import FieldInfo from pydantic.json_schema import GenerateJsonSchema as GenerateJsonSchema from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue @@ -367,6 +370,9 @@ else: class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass + class PydanticUndefinedAnnotation(Exception): # type: ignore[no-redef] + pass + def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, diff --git a/fastapi/utils.py b/fastapi/utils.py index 4c7350fea..a9cfb3387 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -20,6 +20,7 @@ from fastapi._compat import ( BaseConfig, ModelField, PydanticSchemaGenerationError, + PydanticUndefinedAnnotation, Undefined, UndefinedType, Validator, @@ -94,7 +95,7 @@ def create_model_field( ) try: return ModelField(**kwargs) # type: ignore[arg-type] - except (RuntimeError, PydanticSchemaGenerationError): + except (RuntimeError, PydanticSchemaGenerationError, PydanticUndefinedAnnotation): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"check that {type_} is a valid Pydantic field type. "