Search code examples
pythonfastapipydantic

Validate Additional Info Using Pydantic Model


I'm a new user of FastAPI. I'm writing a small web application and I'm wondering if it's good practice to validate additional information, which is not directly related to the object itself, using the Pydantic model itself? For example, checking if a user with such a name exists in the database. For example:

class CreateUser(BaseModel):
    model_config = ConfigDict(strict=True)
    username: str = Field(pattern=r"[0-9a-zA-Z!@#$%&*_.-]{3,}")
    password: str
    secret: str
    
    @field_validator("username")
    def validate_username(cls, value: str):
        # check if user is exist in DB...
        # if no, return the username
        # if yes, raise error

Solution

  • In my opinion you shouldn't do that.

    In FastAPI, to me, Pydantic acts as a gateway to the path operation function(whether it is input or output). It deserializes, cleans(and/or converts) and validates the data so that you can count on that the data you receive is in the good shape. The rest is going to be passed to the path operation function or service layer if you have. I'll decouple the job of checking the availability of the user in database from Pydantic models.