admin管理员组

文章数量:1516870

I encountered the following error while working with FastAPI and Pydantic and SlowApi:

pydantic.errors.PydanticUserError: `TypeAdapter[typing.Annotated[ForwardRef('ResponseModel'), FieldInfo(annotation=ForwardRef('ResponseModel'), required=True)]]` is not fully defined; you should define `typing.Annotated[ForwardRef('ResponseModel'), FieldInfo(annotation=ForwardRef('ResponseModel'), required=True)]` and all referenced types, then call `.rebuild()` on the instance.

Here is my code:

@app.post("/info")
@limiter.limit("5/minute")
async def random_function(
    info: Data,
    request: Request,
) -> ResponseModel:
    if info.name == "test":
        return ResponseModel(id=1)
    return ResponseModel(id=2)

I noticed that:

  • When I remove the rate limiter, the Swagger docs work fine.
  • If I remove Data from the function parameters and keep only Request along with the rate limiter, it also works.

i tried

  • , explicitly call .model_rebuild() on my Pydantic models to resolve forward references. but it didn't slove it

I encountered the following error while working with FastAPI and Pydantic and SlowApi:

pydantic.errors.PydanticUserError: `TypeAdapter[typing.Annotated[ForwardRef('ResponseModel'), FieldInfo(annotation=ForwardRef('ResponseModel'), required=True)]]` is not fully defined; you should define `typing.Annotated[ForwardRef('ResponseModel'), FieldInfo(annotation=ForwardRef('ResponseModel'), required=True)]` and all referenced types, then call `.rebuild()` on the instance.

Here is my code:

@app.post("/info")
@limiter.limit("5/minute")
async def random_function(
    info: Data,
    request: Request,
) -> ResponseModel:
    if info.name == "test":
        return ResponseModel(id=1)
    return ResponseModel(id=2)

I noticed that:

  • When I remove the rate limiter, the Swagger docs work fine.
  • If I remove Data from the function parameters and keep only Request along with the rate limiter, it also works.

i tried

  • , explicitly call .model_rebuild() on my Pydantic models to resolve forward references. but it didn't slove it
Share Improve this question edited Mar 19 at 19:59 Mohanad Gadallah asked Mar 19 at 8:04 Mohanad GadallahMohanad Gadallah 113 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

- After debugging, I found that the issue was caused by the following import:


from _future_ import annotations

When I removed this import, the issue was resolved.

The error occurs because `from _future_ import annotations` enables postponed evaluation of type hints, which can interfere with Pydantic's handling of forward references in certain cases.

To fix this issue:
- Remove the from _future_ import annotations import if it's not necessary.

本文标签: