0
0
FastAPIframework~30 mins

Custom request validation in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom request validation in FastAPI
📖 Scenario: You are building a simple web API to accept user registration data. You want to make sure the data is valid before processing it.
🎯 Goal: Create a FastAPI app that accepts a POST request with user data. Add custom validation to check that the username is at least 3 characters and the age is at least 18.
📋 What You'll Learn
Create a Pydantic model called User with fields username (string) and age (integer).
Add a custom validator to User that checks username length is at least 3 characters.
Add a custom validator to User that checks age is at least 18.
Create a POST endpoint /register that accepts a User model in the request body.
💡 Why This Matters
🌍 Real World
APIs often need to check that incoming data is correct before saving or processing it. Custom validation helps enforce business rules.
💼 Career
Backend developers use FastAPI and Pydantic validation to build reliable and secure APIs that handle user input safely.
Progress0 / 4 steps
1
Create the User model
Create a Pydantic model called User with two fields: username of type str and age of type int.
FastAPI
Need a hint?

Use class User(BaseModel): and define the fields inside.

2
Add custom username validation
Add a custom validator method called validate_username inside the User model using the @validator('username') decorator. It should raise a ValueError if the username length is less than 3 characters.
FastAPI
Need a hint?

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

3
Add custom age validation
Add a custom validator method called validate_age inside the User model using the @validator('age') decorator. It should raise a ValueError if the age is less than 18.
FastAPI
Need a hint?

Use @validator('age') and define a method that checks the age value.

4
Create the POST /register endpoint
Create a POST endpoint /register in the FastAPI app that accepts a User model in the request body and returns the same user data.
FastAPI
Need a hint?

Use @app.post('/register') and define a function that takes user: User and returns it.