Home → Articles → How to Use Pydantic Models with FastAPI to Validate Request Data

How to Use Pydantic Models with FastAPI to Validate Request Data

02 Apr, 2026

Introduction

Pydantic is a data validation library for Python that uses type annotations to define data shapes and enforce rules. When you build APIs with FastAPI, Pydantic models serve as the contract between your application and its clients, ensuring incoming data meets your requirements before your code processes it. This validation layer prevents malformed or incorrect data from reaching your business logic, reducing bugs and improving security. FastAPI integrates Pydantic directly into its request handling pipeline, so you define your data models once and get validation, serialization, and automatic documentation without extra work.

This guide teaches you how to create Pydantic models and use them in FastAPI endpoints for request validation.

Prerequisites

Before you start:

Set Up a Python Virtual Environment

A virtual environment keeps your project dependencies separate from other Python projects on your system. This practice prevents version conflicts and makes your project portable. Create a dedicated directory for your project and set up a virtual environment inside it.

Create a Basic Pydantic Model

A Pydantic model is a Python class that inherits from BaseModel. You define fields using type annotations, and Pydantic automatically checks that incoming data matches those types. To define your first model, create the new main.py file with the Nano text editor.

In this model, name and price are required fields. FastAPI returns a validation error if a request omits them. The is_offer field has a default value of None, making it optional. The | None syntax tells Pydantic this field can accept either a boolean value or None.

Use a Pydantic Model in a POST Endpoint

To validate incoming request data, add a Pydantic model as a parameter to your endpoint function. FastAPI reads the request body, parses it as JSON, and validates it against your model. When validation passes, your function receives an instance of the model with the parsed data. Open the main.py file again to add the endpoint.

When a client sends a POST request to /items/ with a JSON body, FastAPI checks that name exists and is a string, and that price exists and is a number. If validation fails, FastAPI returns a 422 Unprocessable Entity response with details about what went wrong.

Validate Responses with response_model

You can also validate outgoing responses by adding the response_model parameter to your route decorator. This ensures your API returns data in the promised shape and filters out any extra fields you might accidentally include. The response_model parameter accepts a Pydantic model class. Open the main.py file to add an output model.

Using response_model serves two purposes. First, it documents your API's output structure in the automatically generated OpenAPI documentation. Second, it filters response data, preventing extra fields from leaking out. If you return a Response object directly from your endpoint, FastAPI skips response_model validation, so always return the model instance itself.

Add Field Constraints

Pydantic provides the Field function to add validation rules beyond basic type checking. You can enforce minimum and maximum lengths for strings, set numeric ranges, and provide descriptions for documentation. Import Field from pydantic and use it in your model definitions. Open the main.py file to add constrained fields.

Work with Nested Models

Real-world APIs often handle complex, nested data structures. Pydantic lets you define models within models to represent these hierarchies. For a list of nested items, import List from typing and use it as a type annotation. Open the main.py file to add nested models.

In this example, the User model contains a list of Item models. When a client sends JSON with nested items, FastAPI validates each item in the list against the Item model. If any item lacks a required field or has the wrong type, FastAPI returns a validation error.

Create Custom Validators

For validation rules that involve multiple fields, use Pydantic's @model_validator decorator. This decorator runs after individual field validation and lets you check relationships between fields. In Pydantic V2, the @model_validator decorator requires mode='after' to run after all field validations complete. Open the main.py file to add a custom validator.

The @model_validator(mode='after') decorator tells Pydantic to run this method after all field validations succeed. If the validation fails, Pydantic raises a ValueError, and FastAPI converts it to a 422 Unprocessable Entity response.

Test Your API

Create a test file named test_main.py to verify your API works correctly. FastAPI provides a TestClient that simulates HTTP requests without running a server. Create the new test file with the Nano text editor.

Run the FastAPI Application

Start your FastAPI application using Uvicorn, the ASGI server you installed earlier. The --reload flag enables automatic restarts when you change your code, which speeds up development.

console
$ uvicorn main:app --reload

Sample output:

INFO:     Will watch for changes in these directories: ['/home/user/fastapi-pydantic-demo']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [12345] using StatReload
INFO:     Started server process [12346]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

After the server starts, open your web browser to http://localhost:8000/docs. FastAPI automatically generates interactive API documentation from your Pydantic models, showing the expected request and response shapes for every endpoint.

Conclusion

In this guide, you learned how to use Pydantic models with FastAPI to validate request and response data. You created a virtual environment, built models with field constraints using Field, validated responses with response_model, handled nested data structures, and created custom validators for multi-field rules. Now that you have built a validated API, consider integrating a database like PostgreSQL using SQLAlchemy or explore Pydantic's advanced features such as recursive models and custom serialization for more complex scenarios.