Bird
Raised Fist0
FastAPIframework~10 mins

Custom request validation in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom request validation
Receive HTTP Request
↓
Parse JSON Body
↓
Run Custom Validation Function
↓
Process Request
↓
Send Response
The server receives a request, parses the data, runs your custom validation, then either processes or rejects the request.
Execution Sample
FastAPI
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
def create_item(item: Item):
    if item.price <= 0:
        raise HTTPException(status_code=422, detail="Price must be positive")
    return item
This code defines a POST endpoint that checks if the price is positive and rejects the request if not.
Execution Table
StepActionInput DataValidation CheckResultResponse
1Receive request{"name": "Book", "price": 10}N/AData parsedContinue
2Run validationprice=10price > 0?TrueProcess request
3Return responseItem(name='Book', price=10)N/ASuccess200 OK with item data
4Receive request{"name": "Pen", "price": -5}N/AData parsedContinue
5Run validationprice=-5price > 0?FalseReject request
6Return errorN/AN/AValidation failed422 Unprocessable Entity with error detail
💡 Execution stops after sending success or error response based on validation result.
Variable Tracker
VariableStartAfter Step 2 (valid)After Step 5 (invalid)
item.nameN/A"Book""Pen"
item.priceN/A10-5
validation_passedN/ATrueFalse
Key Moments - 2 Insights
Why does the server return a 422 error instead of 200 when price is negative?
Because the custom validation check (step 5) fails (price > 0 is False), the code raises HTTPException causing FastAPI to return 422 as shown in step 6.
What happens if the request JSON is missing the price field?
Pydantic automatically raises a validation error before your custom check, so the request never reaches the custom validation step.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the validation result at step 2?
AError
BTrue
CFalse
DNone
💡 Hint
Check the 'Validation Check' and 'Result' columns at step 2 in the execution_table.
At which step does the server reject the request due to invalid price?
AStep 3
BStep 5
CStep 6
DStep 4
💡 Hint
Look for the step where the response is '422 Unprocessable Entity' in the execution_table.
If the price was zero, how would the validation result change at step 5?
AIt would be False
BIt would be True
CIt would cause a syntax error
DIt would skip validation
💡 Hint
Validation requires price > 0, so zero fails the check as shown in step 5 logic.
Concept Snapshot
Custom request validation in FastAPI:
- Define Pydantic model for request data
- Use endpoint function to receive model instance
- Add if-checks for custom rules
- Raise HTTPException(status_code=422) on failure
- FastAPI returns error response automatically
- Valid requests proceed and return data
Full Transcript
In FastAPI, custom request validation means checking incoming data beyond basic type checks. When a request arrives, FastAPI parses the JSON body into a Pydantic model. Then your code runs extra checks, like ensuring a price is positive. If the check fails, you raise an HTTPException with status 422. FastAPI sends this error back to the client. If the check passes, the request is processed normally and a success response is sent. This flow helps keep your API data clean and reliable.

Practice

(1/5)
1. What is the main purpose of custom request validation in FastAPI?
easy
A. To handle database connections
B. To speed up the API response time
C. To check and enforce rules on incoming data before processing
D. To automatically generate API documentation

Solution

  1. Step 1: Understand the role of validation

    Validation ensures data meets expected rules before using it.
  2. Step 2: Identify FastAPI's validation purpose

    FastAPI uses validation to keep data clean and safe, preventing bad data.
  3. Final Answer:

    To check and enforce rules on incoming data before processing -> Option C
  4. Quick Check:

    Validation = Data rules check [OK]
Hint: Validation means checking data correctness before use [OK]
Common Mistakes:
  • Confusing validation with performance optimization
  • Thinking validation manages database connections
  • Mixing validation with documentation generation
2. Which of the following is the correct way to add a custom validator in a Pydantic model for FastAPI?
easy
A. Override the __init__ method of the model
B. Use @validator decorator inside the model class
C. Add a method named validate() outside the model
D. Use @app.validator decorator in the FastAPI app

Solution

  1. Step 1: Recall Pydantic validation method

    Pydantic uses @validator decorator inside model classes for custom checks.
  2. Step 2: Check other options

    Overriding __init__ or external validate() methods are not standard; @app.validator does not exist.
  3. Final Answer:

    Use @validator decorator inside the model class -> Option B
  4. Quick Check:

    @validator = Custom check inside model [OK]
Hint: Custom validators use @validator inside Pydantic models [OK]
Common Mistakes:
  • Trying to override __init__ for validation
  • Using decorators outside the model class
  • Confusing FastAPI app decorators with Pydantic validators
3. Given this Pydantic model with a custom validator:
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?
medium
A. The endpoint accepts the data and processes it
B. FastAPI ignores the validator and accepts the data
C. The server crashes with an unhandled exception
D. FastAPI returns a 422 error with validation details

Solution

  1. Step 1: Understand the validator logic

    The validator raises ValueError if age is not positive.
  2. Step 2: Know FastAPI's error handling

    FastAPI catches validation errors and returns a 422 response with details.
  3. Final Answer:

    FastAPI returns a 422 error with validation details -> Option D
  4. Quick Check:

    Invalid data triggers 422 error [OK]
Hint: Invalid data triggers 422 error in FastAPI [OK]
Common Mistakes:
  • Assuming server crashes on validation error
  • Thinking FastAPI accepts invalid data silently
  • Confusing 422 with 500 server error
4. Identify the error in this FastAPI custom validation code:
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
medium
A. The validator should raise ValueError, not return it
B. The validator must be a staticmethod, not classmethod
C. The field price should be an int, not float
D. The validator name must start with 'validate_'

Solution

  1. Step 1: Check validator error handling

    Validators must raise exceptions, not return them.
  2. Step 2: Verify other parts

    Validator is correctly a classmethod; price type float is valid; no naming rule requires 'validate_' prefix.
  3. Final Answer:

    The validator should raise ValueError, not return it -> Option A
  4. Quick Check:

    Raise errors in validators, don't return [OK]
Hint: Raise exceptions in validators, don't return them [OK]
Common Mistakes:
  • Returning exceptions instead of raising
  • Confusing @validator with staticmethod
  • Changing field types unnecessarily
5. You want to validate a request body in FastAPI where a user can submit either an email or a phone number, but not both. How can you implement this custom validation in a Pydantic model?
hard
A. Use a root_validator to check that exactly one of email or phone is provided
B. Add separate @validator for email and phone fields to check presence
C. Use FastAPI dependency to validate after model parsing
D. Make both fields required and let FastAPI handle conflicts automatically

Solution

  1. Step 1: Understand the validation requirement

    We need to ensure exactly one of two fields is present, a cross-field check.
  2. Step 2: Choose validation method

    root_validator runs after all fields are parsed and can check multiple fields together.
  3. Step 3: Evaluate other options

    Field validators cannot check other fields; dependency validation is after parsing; making both required contradicts the rule.
  4. Final Answer:

    Use a root_validator to check that exactly one of email or phone is provided -> Option A
  5. Quick Check:

    Cross-field checks use root_validator [OK]
Hint: Use root_validator for checks involving multiple fields [OK]
Common Mistakes:
  • 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
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard