0
0
FastAPIframework~3 mins

Why Custom validation with validator decorator in FastAPI? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple decorator can save you hours of debugging and messy code!

The Scenario

Imagine you have a form where users enter their birthdate, and you want to check if they are at least 18 years old. You write code everywhere to check this manually for every input.

The Problem

Manually checking validation in many places leads to repeated code, mistakes, and inconsistent rules. It's easy to forget a check or write it differently each time.

The Solution

The validator decorator lets you write validation logic once inside your data model. FastAPI runs it automatically whenever data is received, keeping your code clean and consistent.

Before vs After
Before
if user.birthdate > today - timedelta(days=18*365):
    raise ValueError('Must be 18 or older')
After
@validator('birthdate')
def check_age(cls, v):
    from datetime import datetime, timedelta
    today = datetime.today().date()
    if v > today - timedelta(days=18*365):
        raise ValueError('Must be 18 or older')
    return v
What It Enables

This makes your app safer and easier to maintain by centralizing all validation rules in one place.

Real Life Example

When building a signup form, you can ensure all user inputs meet your rules without repeating checks in every route or function.

Key Takeaways

Manual validation is repetitive and error-prone.

The validator decorator centralizes validation logic.

This leads to cleaner, safer, and more maintainable code.