Bird
Raised Fist0
FastAPIframework~20 mins

Custom validators in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Validator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What output does this FastAPI Pydantic model produce when invalid data is sent?
Consider this FastAPI Pydantic model with a custom validator. What happens if the input JSON is {"age": 15}?
FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    age: int

    @validator('age')
    def check_age(cls, v):
        if v < 18:
            raise ValueError('Must be at least 18')
        return v

user = User(age=15)
ACreates User instance with age 15 without error
BRaises ValueError with message 'Must be at least 18'
CRaises TypeError because age is int but validator returns null
DRaises ValidationError from Pydantic with message about age
Attempts:
2 left
💡 Hint
Think about how Pydantic handles validation errors inside models.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a Pydantic custom validator for multiple fields?
You want to create a validator that checks two fields together in a Pydantic model. Which code snippet is correct?
FastAPI
from pydantic import BaseModel, root_validator

class Data(BaseModel):
    start: int
    end: int

    @root_validator
    def check_start_end(cls, values):
        start, end = values.get('start'), values.get('end')
        if start >= end:
            raise ValueError('start must be less than end')
        return values
A@root_validator\ndef check_start_end(cls, values):\n start, end = values.get('start'), values.get('end')\n if start >= end:\n raise ValueError('start must be less than end')\n return values
B@root_validator(pre=True)\ndef check(cls, values):\n if values['start'] >= values['end']:\n raise ValueError('start must be less than end')\n return values
C@validator(['start', 'end'])\ndef check(cls, v):\n if v['start'] >= v['end']:\n raise ValueError('start must be less than end')\n return v
D@validator('start', 'end')\ndef check(cls, v):\n if v < 0:\n raise ValueError('Negative not allowed')\n return v
Attempts:
2 left
💡 Hint
Use root_validator to validate multiple fields together.
🔧 Debug
advanced
2:00remaining
Why does this custom validator not run in FastAPI?
Given this Pydantic model, why does the custom validator not execute when creating an instance?
FastAPI
from pydantic import BaseModel, validator

class Item(BaseModel):
    name: str

    @validator('name')
    def name_must_not_be_empty(cls, value):
        if not value:
            raise ValueError('Name cannot be empty')
        return value

item = Item(name=None)
AValidator does not run because the decorator is missing parentheses
BValidator does not run because null is not allowed by default for str fields
CValidator runs but raises TypeError because null is not a string
DValidator runs and raises ValueError as expected
Attempts:
2 left
💡 Hint
Check how Pydantic treats null values for required fields.
❓ state_output
advanced
2:00remaining
What is the value of 'email' after validation in this FastAPI model?
This Pydantic model uses a custom validator to normalize emails. What is the value of user.email after creating User(email=' EXAMPLE@Domain.COM ')?
FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    email: str

    @validator('email')
    def normalize_email(cls, v):
        return v.strip().lower()

user = User(email='  EXAMPLE@Domain.COM  ')
result = user.email
A'EXAMPLE@Domain.COM'
B' EXAMPLE@Domain.COM '
C'example@domain.com'
DRaises ValidationError
Attempts:
2 left
💡 Hint
Look at what the validator returns after stripping and lowering.
🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI custom validators is true?
Select the correct statement about how custom validators work in FastAPI's Pydantic models.
ACustom validators run after type validation and receive already converted Python types.
BCustom validators must always return null to indicate success.
CCustom validators run before type validation and can modify raw input data.
DCustom validators can only validate single fields, not multiple fields together.
Attempts:
2 left
💡 Hint
Think about when validators run in Pydantic's validation process.

Practice

(1/5)
1. What is the main purpose of using @validator in FastAPI models?
easy
A. To connect the model to a database
B. To automatically generate API documentation
C. To add custom rules that check if input data is valid
D. To style the API response format

Solution

  1. Step 1: Understand the role of @validator

    The @validator decorator is used to add custom validation logic to model fields in FastAPI.
  2. Step 2: Identify the purpose of validation

    Validation ensures that the data meets specific rules before the app processes it, helping keep input correct and safe.
  3. Final Answer:

    To add custom rules that check if input data is valid -> Option C
  4. Quick Check:

    Custom validation = check input rules [OK]
Hint: Validators check data rules before use [OK]
Common Mistakes:
  • Confusing validators with database connectors
  • Thinking validators generate docs
  • Assuming validators change response style
2. Which of the following is the correct way to define a custom validator for a Pydantic model field named age?
easy
A. @validator('age')\ndef check_age(cls, value):
B. def validate_age(cls, value):
C. @validate('age')\ndef age_validator(cls, value):
D. @validate_field('age')\ndef age_check(cls, value):

Solution

  1. Step 1: Recall the correct decorator syntax

    FastAPI uses Pydantic's @validator decorator with the field name as a string argument.
  2. Step 2: Match the function definition style

    The validator function must be a class method with parameters cls and value.
  3. Final Answer:

    @validator('age')\ndef check_age(cls, value): -> Option A
  4. Quick Check:

    Use @validator('field') with cls, value [OK]
Hint: Use @validator('field') decorator for custom checks [OK]
Common Mistakes:
  • Using @validate instead of @validator
  • Missing the field name in decorator
  • Wrong function parameters
3. Given this code snippet, what will be the output if age is set to 15?
from pydantic import BaseModel, validator

class User(BaseModel):
    age: int

    @validator('age')
    def check_age(cls, value):
        if value < 18:
            raise ValueError('Must be 18 or older')
        return value

try:
    user = User(age=15)
except Exception as e:
    print(e)
medium
A. Must be 18 or older
B. TypeError because age is int
C. User object with age 15 is created
D. No output, code runs silently

Solution

  1. Step 1: Analyze the validator logic

    The validator checks if age is less than 18 and raises a ValueError if true.
  2. Step 2: Check the input value

    Since age=15 is less than 18, the validator raises the error.
  3. Final Answer:

    Must be 18 or older -> Option A
  4. Quick Check:

    Age < 18 triggers ValueError [OK]
Hint: Validator raises error if condition fails [OK]
Common Mistakes:
  • Assuming object creates despite validation error
  • Confusing ValueError with TypeError
  • Ignoring the exception handling block
4. Identify the error in this custom validator code:
from pydantic import BaseModel, validator

class Product(BaseModel):
    price: float

    @validator('price')
    def check_price(value):
        if value <= 0:
            raise ValueError('Price must be positive')
        return value
medium
A. Validator method must return None
B. Missing cls parameter in validator method
C. Price field should be int, not float
D. Validator decorator should be @validate

Solution

  1. Step 1: Check validator method signature

    Validator methods must accept cls as the first parameter, then value.
  2. Step 2: Identify missing parameter

    The method check_price only has value, missing cls.
  3. Final Answer:

    Missing cls parameter in validator method -> Option B
  4. Quick Check:

    Validator needs cls, value parameters [OK]
Hint: Validator methods need cls first, then value [OK]
Common Mistakes:
  • Omitting cls parameter
  • Using wrong decorator name
  • Returning None instead of value
5. You want to create a custom validator that ensures a username is lowercase and at least 3 characters long. Which code correctly implements this in a FastAPI Pydantic model?
from pydantic import BaseModel, validator

class User(BaseModel):
    username: str

    @validator('username')
    def validate_username(cls, value):
        # Fill in validation logic here
        pass
hard
A. if len(value) < 3 and not value.islower():\n raise ValueError('Username must be lowercase and 3+ chars')\nreturn value
B. if len(value) < 3 and value.islower():\n raise ValueError('Username too short')\nreturn value
C. if len(value) > 3 and value.islower():\n return value\nelse:\n raise ValueError('Invalid username')
D. if value.islower() and len(value) >= 3:\n return value\nraise ValueError('Username invalid')

Solution

  1. Step 1: Understand validation requirements

    The username must be lowercase and at least 3 characters long.
  2. Step 2: Check each option logic

    if value.islower() and len(value) >= 3:\n return value\nraise ValueError('Username invalid') correctly checks both conditions and raises error if not met, returning value otherwise.
  3. Final Answer:

    if value.islower() and len(value) >= 3:\n return value\nraise ValueError('Username invalid') -> Option D
  4. Quick Check:

    Check both conditions, raise error if false [OK]
Hint: Check all conditions with 'and', raise error if false [OK]
Common Mistakes:
  • Using 'or' instead of 'and' causing wrong logic
  • Returning value inside else but missing return in if
  • Incorrect length comparison operators
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