0
0
FastAPIframework~5 mins

Custom request validation in FastAPI

Choose your learning style9 modes available
Introduction

Custom request validation helps you check if the data sent to your API is correct and safe before using it.

When you want to make sure a user's input follows specific rules not covered by default checks.
When you need to validate complex data structures or relationships between fields.
When you want to give clear error messages if the input is wrong.
When you want to prevent bad data from causing errors in your app.
When you want to enforce business rules on incoming data.
Syntax
FastAPI
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, validator

class Item(BaseModel):
    name: str
    price: float

    @validator('price')
    def price_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Price must be positive')
        return v

app = FastAPI()

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

Use @validator decorator inside Pydantic models to add custom checks.

Raise ValueError with a message to show validation errors.

Examples
This example checks that the user's age is 18 or older.
FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    username: str
    age: int

    @validator('age')
    def age_must_be_adult(cls, v):
        if v < 18:
            raise ValueError('User must be at least 18 years old')
        return v
This example uses @root_validator to check a rule involving multiple fields together.
FastAPI
from pydantic import BaseModel, root_validator

class Order(BaseModel):
    quantity: int
    price_per_item: float

    @root_validator
    def check_total_price(cls, values):
        quantity = values.get('quantity')
        price = values.get('price_per_item')
        if quantity is not None and price is not None and quantity * price > 1000:
            raise ValueError('Total price must not exceed 1000')
        return values
Sample Program

This FastAPI app defines a Product model with a custom validator to ensure the price is positive. When you send a POST request to /products/ with product data, it checks the price. If the price is zero or negative, it returns an error. Otherwise, it confirms creation.

FastAPI
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, validator

class Product(BaseModel):
    name: str
    price: float

    @validator('price')
    def price_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Price must be positive')
        return v

app = FastAPI()

@app.post('/products/')
async def create_product(product: Product):
    return {'message': f'Product {product.name} with price {product.price} created successfully'}
OutputSuccess
Important Notes

Custom validators run automatically when FastAPI parses the request body.

Validation errors return clear HTTP 422 responses with details.

You can use @root_validator to check multiple fields at once.

Summary

Custom request validation helps keep your API data clean and safe.

Use Pydantic validators inside your data models for easy checks.

FastAPI automatically handles validation errors and responses.