0
0
FastAPIframework~20 mins

Custom validators in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 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.