First check
- [ x ] I added a very descriptive title to this issue.
- [ x ] I used the GitHub search to find a similar issue and didn't find it.
- [ x ] I searched the FastAPI documentation, with the integrated search.
- [ x ] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [ x ] I already read and followed all the tutorial in the docs and didn't find an answer.
- [ x ] I already checked if it is not related to FastAPI but to Pydantic.
- [ x ] I already checked if it is not related to FastAPI but to Swagger UI.
- [ x ] I already checked if it is not related to FastAPI but to ReDoc.
- [ x ] After submitting this, I commit to one of:
- Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
- I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
- Implement a Pull Request for a confirmed bug.
Example
Here's a self-contained, minimal, reproducible, example with my use case:
from fastapi import FastAPI
from pydantic import BaseModel, root_validator
from typing import Optional, Dict, Any
app = FastAPI()
class UserUpdate(BaseModel):
password: Optional[str]
name: Optional[str]
@root_validator
def validate(cls, values: Dict[str, Any]) -> Dict[str, Any]:
return values
@app.patch("/me", response_model=schemas.User)
def update_user_me(
user_in: UserUpdate,
) -> Any:
assert isinstance(user_in, dict)
return user_in
Description
- Using root_validator in the pydantic model changes the behavior of the dependency injection, instead of return an instance of UserUpdate, a dict is returned
- Commenting out the root_validator in the pydantic model leads to the expected behavior, in this case user_in is an instance of UserUpdate
- I would expect user_in to be of type UserUpdate
Environment
Most helpful comment
You should rename your "def validate" to something else (like "def _validate"). "validate" is an existing method for pydantic's BaseModel, so you are overriding it with yours, causing that unexpected behaviour. I tried it and after renaming the root_validator function name, it works as expected.