1. Input validation in FastAPI
Let's learn how to define custom rules for input validation with FastAPI.
2. Validating input data
This is the second step in our prediction workflow.
3. Why validate the input?
Input validation is crucial for maintaining data integrity and preventing errors in our application. FastAPI integrates fully with Pydantic, providing powerful tools for data validation.
4. Pydantic for pre-defined function
By the end of this video, we'll be able to use Pydantic's field validators to customize and add metadata to fields of models.
5. Custom validation with pydantic
We'll also learn to create custom domain-specific validators to perform specific validations in a precise scope.
6. Graceful error reporting
And handle validation errors by providing customized, user-friendly error messages.
7. Pydantic field validators
Let's say we have a user registration endpoint. While signing up, we need to ensure the username fits a certain character limit.
We can use Pydantic's field validators to validate the user's input for their usernames.
These validators allow us to set constraints on our data models.
Here, we have created a User data model which inherits from BaseModel. We add a field called username where the three dots notation signifies that the username field is required, meaning the username must be provided whenever we instantiate the model. We're ensuring the username is minimum 3 and maximum 50 characters using the min_length and max_length parameters.
That's how we can validate input attributes using Pydantic's Field.
8. Adding custom validators
But many times, we need more complex validation logic. That's where custom validators come in.
We added age as a new user attribute in the user model, and age should be a reasonable number. In this case we want age to be at least 13.
We use the validator decorator on the age field that is to be validated, followed by the function age_criteria specifying the custom condition, that is, the age should not be less than 13.
9. Custom validators in action
So, if the user's age is at least 13, we create the user.
If it is not, we raise a value error explaining the issue.
10. Putting it all together
Let's see how all of this comes together in a FastAPI route. We have defined our Pydantic user model with a custom validator for the age field. Whenever a user is instantiated, the validations are performed. If it's not, the function raises a ValueError with a custom message.
11. Putting it all together
Now we can define a POST endpoint at slash users. It takes user details which are of type User (our Pydantic model). FastAPI will automatically validate the incoming data against the User model, including running our custom validators.
If all validations pass, the function returns a JSON response with a success message and the validated user data. If validations fail, an error message will be returned.
12. Let's practice!
Time to practice basic validation!