0
0
FastAPIframework~20 mins

Custom validation with validator decorator in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Validator Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when invalid data is passed to this Pydantic model?

Consider this FastAPI Pydantic model using a @validator decorator:

from pydantic import BaseModel, validator

class User(BaseModel):
    username: str
    age: int

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

user = User(username='alice', age=16)

What will happen when this code runs?

FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    username: str
    age: int

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

user = User(username='alice', age=16)
AIt raises a ValueError with message 'Must be at least 18' during model creation.
BIt creates the User object with age 16 without error.
CIt raises a TypeError because age is not a string.
DIt ignores the validator and sets age to 16.
Attempts:
2 left
💡 Hint

Think about what the validator function does when the age is less than 18.

📝 Syntax
intermediate
2:00remaining
Which option correctly uses the validator decorator to check multiple fields?

You want to validate that start_date is before end_date in a Pydantic model. Which code snippet correctly implements this using @validator?

FastAPI
from pydantic import BaseModel, validator
from datetime import date

class Event(BaseModel):
    start_date: date
    end_date: date

    # Your validator here
A
    @validator('end_date')
    def check_dates(cls, v, values):
        if 'start_date' in values and v &lt;= values['start_date']:
            raise ValueError('end_date must be after start_date')
        return v
B
    @validator('start_date', 'end_date')
    def check_dates(cls, v):
        if v['start_date'] &gt;= v['end_date']:
            raise ValueError('start_date must be before end_date')
        return v
C
    @validator('start_date')
    def check_dates(cls, v, values):
        if v &gt;= values['end_date']:
            raise ValueError('start_date must be before end_date')
        return v
D
    @validator('start_date', 'end_date')
    def check_dates(cls, start, end):
        if start &gt;= end:
            raise ValueError('start_date must be before end_date')
        return start
Attempts:
2 left
💡 Hint

Remember the validator receives the current field value and a dict of previously validated fields.

🔧 Debug
advanced
2:00remaining
Why does this validator not run as expected?

Look at this Pydantic model:

from pydantic import BaseModel, validator

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

    @validator('price')
    def price_positive(cls, value):
        if value <= 0:
            raise ValueError('Price must be positive')

product = Product(name='Book', price=0)

Why does this code raise no error even though price is 0?

FastAPI
from pydantic import BaseModel, validator

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

    @validator('price')
    def price_positive(cls, value):
        if value <= 0:
            raise ValueError('Price must be positive')

product = Product(name='Book', price=0)
AThe validator decorator is missing parentheses, so it is not applied.
BThe error is raised but caught internally by Pydantic, so no exception shows.
CThe price field is not declared as Optional, so validation is ignored.
DThe validator function does not return the value, so validation is skipped silently.
Attempts:
2 left
💡 Hint

Check what the validator function returns.

state_output
advanced
2:00remaining
What is the value of 'email' after model creation?

Given this Pydantic model:

from pydantic import BaseModel, validator

class User(BaseModel):
    email: str

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

user = User(email='  EXAMPLE@DOMAIN.COM  ')

What is the value of user.email?

FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    email: str

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

user = User(email='  EXAMPLE@DOMAIN.COM  ')
result = user.email
ARaises a ValueError because of whitespace
B' EXAMPLE@DOMAIN.COM '
C'example@domain.com'
D'EXAMPLE@DOMAIN.COM'
Attempts:
2 left
💡 Hint

Think about what lower() and strip() do to the string.

🧠 Conceptual
expert
2:00remaining
Which statement about Pydantic's @validator decorator is TRUE?

Choose the correct statement about how the @validator decorator works in Pydantic models.

AValidators must always be instance methods and cannot be class methods.
BValidators can access other fields' values only if those fields are validated before the current field.
CValidators run after the entire model is created and can modify any field arbitrarily.
DValidators automatically run asynchronously if the decorated method is async.
Attempts:
2 left
💡 Hint

Consider the order of field validation and how values parameter works.