0
0
FastAPIframework~30 mins

Custom validators in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Validators in FastAPI
📖 Scenario: You are building a simple FastAPI app to register users. You want to make sure the user's age is valid and the username follows specific rules.
🎯 Goal: Create a FastAPI app with a user model that uses custom validators to check the age and username fields.
📋 What You'll Learn
Create a Pydantic model called User with fields username (string) and age (integer).
Add a custom validator to ensure age is at least 18.
Add a custom validator to ensure username contains only letters and numbers.
Create a FastAPI app with a POST endpoint /register that accepts a User model.
💡 Why This Matters
🌍 Real World
Custom validators help ensure user input meets specific rules before saving or processing, improving data quality.
💼 Career
Backend developers often write custom validators in FastAPI or similar frameworks to enforce business rules and prevent bad data.
Progress0 / 4 steps
1
Create the User model with fields
Create a Pydantic model called User with two fields: username as a string and age as an integer.
FastAPI
Need a hint?

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

2
Add a custom validator for age
Add a custom validator method called check_age inside the User model that ensures age is at least 18. Use the @validator('age') decorator from Pydantic.
FastAPI
Need a hint?

Use @validator('age') and define a method that raises ValueError if age is less than 18.

3
Add a custom validator for username
Add a custom validator method called check_username inside the User model that ensures username contains only letters and numbers. Use @validator('username') and Python's isalnum() method.
FastAPI
Need a hint?

Use @validator('username') and check if value.isalnum() is False. Raise ValueError if so.

4
Create FastAPI app with /register endpoint
Create a FastAPI app instance called app. Add a POST endpoint /register that accepts a User model as JSON and returns the same user data.
FastAPI
Need a hint?

Create app = FastAPI(). Use @app.post('/register') and define an async function register that takes user: User and returns it.