最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

I encountered a Swagger error when using from __future__ import annotations with Pydantic, FastAPI, and SlowAPI in my project -

programmeradmin0浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论