Discover how to stop chasing bugs caused by bad data with one simple technique!
Why Custom request validation in FastAPI? - Purpose & Use Cases
Imagine building an API where users send data, and you have to check every detail manually to make sure it's correct before saving it.
Manually checking each piece of data is slow, easy to forget, and can lead to bugs or security holes if you miss something.
Custom request validation lets you define clear rules once, so FastAPI automatically checks incoming data and gives helpful errors if something is wrong.
if not isinstance(data['age'], int) or data['age'] < 0: return {'error': 'Invalid age'}
from pydantic import BaseModel, validator class User(BaseModel): age: int @validator('age') def age_must_be_positive(cls, v): if v < 0: raise ValueError('Age must be positive') return v
You can build APIs that automatically catch bad data early, making your app safer and easier to maintain.
Think of an online signup form where users must enter their birthdate correctly; custom validation ensures no impossible dates get saved.
Manual data checks are slow and error-prone.
Custom validation automates and centralizes data rules.
This leads to safer, cleaner, and more reliable APIs.
Practice
Solution
Step 1: Understand the role of validation
Validation ensures data meets expected rules before using it.Step 2: Identify FastAPI's validation purpose
FastAPI uses validation to keep data clean and safe, preventing bad data.Final Answer:
To check and enforce rules on incoming data before processing -> Option CQuick Check:
Validation = Data rules check [OK]
- Confusing validation with performance optimization
- Thinking validation manages database connections
- Mixing validation with documentation generation
Solution
Step 1: Recall Pydantic validation method
Pydantic uses @validator decorator inside model classes for custom checks.Step 2: Check other options
Overriding __init__ or external validate() methods are not standard; @app.validator does not exist.Final Answer:
Use @validator decorator inside the model class -> Option BQuick Check:
@validator = Custom check inside model [OK]
- Trying to override __init__ for validation
- Using decorators outside the model class
- Confusing FastAPI app decorators with Pydantic validators
from pydantic import BaseModel, validator
class User(BaseModel):
age: int
@validator('age')
def age_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Age must be positive')
return v
What happens if a request sends
{"age": -5} to a FastAPI endpoint using this model?Solution
Step 1: Understand the validator logic
The validator raises ValueError if age is not positive.Step 2: Know FastAPI's error handling
FastAPI catches validation errors and returns a 422 response with details.Final Answer:
FastAPI returns a 422 error with validation details -> Option DQuick Check:
Invalid data triggers 422 error [OK]
- Assuming server crashes on validation error
- Thinking FastAPI accepts invalid data silently
- Confusing 422 with 500 server error
from pydantic import BaseModel, validator
class Item(BaseModel):
price: float
@validator('price')
def check_price(cls, value):
if value < 0:
return ValueError('Price must be non-negative')
return value
Solution
Step 1: Check validator error handling
Validators must raise exceptions, not return them.Step 2: Verify other parts
Validator is correctly a classmethod; price type float is valid; no naming rule requires 'validate_' prefix.Final Answer:
The validator should raise ValueError, not return it -> Option AQuick Check:
Raise errors in validators, don't return [OK]
- Returning exceptions instead of raising
- Confusing @validator with staticmethod
- Changing field types unnecessarily
Solution
Step 1: Understand the validation requirement
We need to ensure exactly one of two fields is present, a cross-field check.Step 2: Choose validation method
root_validator runs after all fields are parsed and can check multiple fields together.Step 3: Evaluate other options
Field validators cannot check other fields; dependency validation is after parsing; making both required contradicts the rule.Final Answer:
Use a root_validator to check that exactly one of email or phone is provided -> Option AQuick Check:
Cross-field checks use root_validator [OK]
- Trying to check multiple fields in single field validators
- Relying on FastAPI dependencies for core validation
- Making both fields required when only one should be
Ready to prove it?
Pass the test and this pattern moves unknown
