As introduced earlier, FastAPI relies heavily on Pydantic for data validation. At the heart of this system are Pydantic models, which are essentially Python classes you define to specify the structure and data types of the information your API expects to receive or send.
Think of a Pydantic model as a blueprint for your data. By defining a model, you declare the "shape" of the data, including the names of the fields (keys in a JSON object, for example) and the expected Python type for each field's value (like int
, float
, str
, bool
, or even more complex types like List
or other Pydantic models).
BaseModel
To define a data model, you create a class that inherits from Pydantic's BaseModel
. Inside this class, you declare attributes using standard Python type annotations.
Let's consider a simple example. Imagine you have a machine learning model that predicts whether a customer will click on an ad based on their age and previous interaction history (represented by a boolean). You can define a Pydantic model for the input data like this:
from pydantic import BaseModel
class AdPredictionInput(BaseModel):
age: int
previous_interaction: bool
campaign_id: str | None = None # Optional field with a default value
In this AdPredictionInput
model:
BaseModel
.age
, previous_interaction
, and campaign_id
.age
is declared with the type hint int
, meaning Pydantic (and FastAPI) will expect an integer value for this field.previous_interaction
is declared as bool
, expecting a boolean (true
or false
in JSON).campaign_id
uses str | None = None
. This signifies that the field expects a string, but it's also optional. If it's not provided in the incoming data, it will default to None
.When you use a Pydantic model like AdPredictionInput
as a type hint for a parameter in your FastAPI path operation function (which we'll cover in detail soon), FastAPI automatically performs the following:
AdPredictionInput
in our example).
age
and previous_interaction
?age
an integer (or convertible to one)?previous_interaction
a boolean (or convertible to one)?campaign_id
is present, is it a string?This declarative approach using BaseModel
and type hints significantly simplifies data validation. You define the expected structure once, and FastAPI handles the enforcement, making your API endpoints cleaner and more focused on the core logic, like interacting with your machine learning model. In the following sections, we'll explore how to apply these models to request bodies, responses, and other parameter types.
© 2025 ApX Machine Learning