Using Pydantic with FastAPI for Model Creation and Data Validation

FastAPI, a modern Python web framework, is widely recognized for its high performance and ease of use. One of the key reasons for its popularity is its tight integration with Pydantic, a powerful library for data validation and settings management. In this blog, we will explore how to use Pydantic with FastAPI for creating models and validating data, complete with detailed explanations and practical examples.

Why Pydantic?

Pydantic is a data validation and parsing library that leverages Python’s type hints. It ensures that the data used in your application adheres to the specified schema, making your code more robust and reducing runtime errors.

Key Features of Pydantic

  1. Type-Safe Data Parsing: Automatically parses data into the correct types.
  2. Data Validation: Ensures that input data conforms to predefined rules.
  3. Serialization: Converts data models to JSON with ease.
  4. Integration with FastAPI: Seamlessly integrates with FastAPI for request validation and response generation.

Related read: An Introduction to FastAPI, a Powerful Python Framework

Setting Up FastAPI with Pydantic

Installation

Before diving into the code, ensure you have FastAPI and Uvicorn installed:

pip install fastapi uvicorn

Pydantic is automatically installed as a dependency of FastAPI, so you don’t need to install it separately.

Creating a Pydantic Model

In FastAPI, Pydantic models are used to define the structure of request and response data. Here is a simple example:

➡️ Example: Defining a User Model

from pydantic import BaseModel, EmailStr

class User(BaseModel):
       id: int
       name: str
       email: EmailStr
       age: int
       is_active: bool = True

Explanation

  1. BaseModel: All Pydantic models inherit from BaseModel.
  2. Field Types: Use Python type hints (int, str, etc.) to define field types.
  3. Default Values: Set default values for fields (is_active defaults to True).
  4. Validation: Built-in types like EmailStr validate email addresses automatically.

Using Pydantic Models in FastAPI

Pydantic models can be used in FastAPI to validate request payloads and structure responses.

➡️ Example: Creating an API Endpoint

from fastapi import FastAPI
from typing import List


app = FastAPI()


# Sample database (in-memory list)
users = []


@app.post("/users/", response_model=User)
def create_user(user: User):
     users.append(user)
     return user


@app.get("/users/", response_model=List[User])
def get_users():
     return users

Explanation

  1. Request Body: In the create_user endpoint, the user parameter is automatically validated against the User model.
  2. Response Model: The response_model parameter ensures the response data adheres to the User model.
  3. List of Models: The get_users endpoint returns a list of User models.

Advanced Validation with Pydantic

Nested Models

Pydantic supports nested models, allowing you to create complex data structures.

➡️ Example: Order with Nested User Model

from typing import List


class OrderItem(BaseModel):
     item_id: int
     quantity: int


class Order(BaseModel):
     order_id: int
     user: User
     items: List[OrderItem]

Explanation

  1. Nested Model: The user field in Order references the User model.
  2. Lists of Models: The items field is a list of OrderItem models.

Ensure Data Integrity & Performance with Our API Validation and Optimization Solutions

Field Validation and Aliases

Pydantic allows you to customize field behavior using the Field class.

➡️ Example: Using Field for Validation

from pydantic import BaseModel, Field

class BlogPost(BaseModel):
      title: str = Field(..., max_length=100)
      content: str
      published_at: str = Field(..., alias="publishedAt")

Explanation

  1. Field Constraints: max_length=100 restricts the title to 100 characters.
  2. Aliases: The alias parameter maps JSON keys to field names (e.g., publishedAt to published_at).

Error Handling

When validation fails, FastAPI automatically returns a detailed error response.

➡️ Example: Validation Error Response

If you send invalid data to an endpoint:

{
  "detail": [
{
  "loc": ["body", "email"],
  "msg": "value is not a valid email address",
  "type": "value_error.email"
}
  ]
}

This detailed response helps in debugging and provides clear feedback to API consumers.

coma

Conclusion

Using Pydantic with FastAPI simplifies data validation and model creation, making your applications more reliable and maintainable. With its powerful features like type-safe validation, nested models, and custom validators, Pydantic enables you to handle complex data structures effortlessly. By leveraging these capabilities, you can build robust APIs that provide an excellent developer and user experience.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?