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 onlyRequest
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 onlyRequest
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
1 Answer
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.