Validating Data with Pydantic Models

Validating Data with Pydantic Models

Welcome back! In our previous lessons, we worked with FastAPI and Pydantic models. We learned how to model our data and how to handle POST requests. Today, we move a step further. We're going to talk about a crucial aspect of handling data, particularly incoming data, which is data validation.

Pydantic models not only help us structure our data but also validate it. They ensure that the incoming data follow the model's defined framework and that our application can handle it without trouble.

Importance of Data Validation

In any application, the data we receive is prone to inconsistencies. For instance, imagine you have a form on a website, and you're expecting a user to enter their name. A name is usually a string of alphabets, maybe a dash or an apostrophe. But what if a user tries to enter a number as their name, or some sort of special character? This input is not ideal and can lead to problems in the application if not handled correctly.

That's where data validation comes in. It's the process of checking if the data provided matches the requirements we set. It ensures that our application data adheres to the defined business rules and logic.

Data Validation with Pydantic Models

Pydantic allows us to set constraints on our data fields using the Field class, which provides a way to specify additional validation and metadata for model fields.

For example, let’s suppose we have a field for the experience of a crew member, which is an integer. We want to ensure that the value entered for this field is greater than zero. We can easily define this requirement using the Pydantic model:

from pydantic import BaseModel, Field

class CrewMember(BaseModel):
    name: str
    role: str
    experience: int = Field(..., gt=0)

In this example gt=0 is used to enforce that the experience must be a value greater than zero, while the ... indicates that the experience field is mandatory and must be provided when creating an instance of the CrewMember model. This is a shorthand way in Pydantic to mark a field as required.

Let's explore some additional examples of data validation!

Validating String Length

Let's say we have a title field that should not exceed 100 characters. We can use max_length to enforce this constraint.

from pydantic import BaseModel, Field

class Book(BaseModel):
    title: str = Field(..., max_length=100)
    author: str
    pages: int

This ensures that any data provided for the title field will not exceed 100 characters.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal