Skip to main content

Understanding Pydantic models

Introduction

Pydantic is a data validation library that plays a crucial role in FastAPI. Models in Pydantic are classes that inherit from the BaseModel class, which allow structured data in a way that could be checked and validated.

Basic Pydantic Model

To start the exploration of Pydantic models, let's create a simple model.

from pydantic import BaseModel

class Item(BaseModel):
name: str
description: str = None
price: float
quantity: int

In the above code snippet, Item is a Pydantic model with attributes name, description, price, and quantity. The type annotations are not just for IDEs or linters, but they have a functional purpose. They define the data types each field should have.

Default Values

You can set default values to the fields which will be used if no data is provided while creating an object of that class. In the above example, description attribute has a default value of None.

Validation with Pydantic Models

One significant advantage of using Pydantic models is their ability to validate data types. Let's see an example:

item1 = Item(name="Fridge", price=1500.00, quantity=1)

This is a valid Item. If you try creating an Item with a price that is not a float, Pydantic will raise an error.

Using Pydantic models with FastAPI

FastAPI works seamlessly with Pydantic models. FastAPI uses Pydantic models to perform request body validations and even shape the response data. Let's see an example of how to use a Pydantic model in FastAPI:

from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
name: str
description: str = None
price: float
quantity: int

app = FastAPI()

@app.post("/items/")
async def create_item(item: Item):
return item

In the create_item function, the parameter item is typed as Item. When a request is sent to this endpoint including a JSON body, FastAPI will:

  1. Parse the JSON body.
  2. Validate the data with the Item model.
  3. Give you the resulting object of the Item model to use in your function.

Nested Pydantic Models

Pydantic models can be nested to create more complex data structures. Here's an example:

from pydantic import BaseModel

class Manufacturer(BaseModel):
name: str
location: str

class Item(BaseModel):
name: str
description: str = None
price: float
quantity: int
manufacturer: Manufacturer

In the above example, Item contains an attribute manufacturer which is a Pydantic model itself.

Conclusion

Pydantic models are an integral part of FastAPI. They provide a structured way to define and validate data, making sure you are always working with the correct data types. They also allow shaping the JSON responses to match these models, creating a robust and error-free API.


I hope this tutorial helps you get a better understanding of Pydantic models in FastAPI. Happy coding!