0
0
FastAPIframework~30 mins

Custom validation with validator decorator in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom validation with validator decorator in FastAPI
📖 Scenario: You are building a simple FastAPI app to register users. You want to make sure the user's username is at least 3 characters long and contains only letters and numbers.
🎯 Goal: Create a Pydantic model with a custom validator using the @validator decorator to check the username field. The validator should raise an error if the username is too short or contains invalid characters.
📋 What You'll Learn
Create a Pydantic model called User with a username field of type str.
Add a class method decorated with @validator('username') to validate the username.
The validator must check that username is at least 3 characters long.
The validator must check that username contains only letters and numbers.
Raise a ValueError with a clear message if validation fails.
💡 Why This Matters
🌍 Real World
Custom validation is essential in web APIs to ensure user input meets rules before saving or processing. This prevents errors and security issues.
💼 Career
Backend developers often write custom validators in FastAPI or similar frameworks to enforce business rules and data integrity.
Progress0 / 4 steps
1
Create the User model with username field
Create a Pydantic model called User with a single field username of type str.
FastAPI
Need a hint?

Use class User(BaseModel): and define username: str inside.

2
Import the validator decorator
Add an import statement to import validator from pydantic.
FastAPI
Need a hint?

Use from pydantic import validator to import the decorator.

3
Add a custom validator for username
Inside the User model, add a class method decorated with @validator('username') named check_username. It should accept cls and value parameters. Check if value is at least 3 characters long and contains only letters and numbers using value.isalnum(). If not, raise ValueError with the message 'Username must be at least 3 characters and alphanumeric'. Return value if valid.
FastAPI
Need a hint?

Use @validator('username') above a method that checks length and isalnum().

4
Complete the FastAPI app with POST endpoint
Add the necessary imports from fastapi and create a FastAPI app instance called app. Add a POST endpoint /users/ that accepts a User model as input and returns the same User object as JSON.
FastAPI
Need a hint?

Import FastAPI, create app = FastAPI(), then add a POST route /users/ that returns the User object.