0
0
FastAPIframework~10 mins

Custom validation with validator decorator in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the validator decorator from pydantic.

FastAPI
from pydantic import BaseModel, [1]
Drag options to blanks, or click blank then click option'
Avalidate_field
Bvalidate
Ccheck
Dvalidator
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'validate' instead of 'validator' causes import errors.
Trying to import a non-existent decorator like 'check'.
2fill in blank
medium

Complete the method decorator to validate the 'name' field.

FastAPI
class User(BaseModel):
    name: str

    @[1]('name')
    def name_must_be_capitalized(cls, v):
        if not v.istitle():
            raise ValueError('Name must be capitalized')
        return v
Drag options to blanks, or click blank then click option'
Avalidate
Bvalidator
Ccheck
Dvalidate_field
Attempts:
3 left
💡 Hint
Common Mistakes
Using '@validate' instead of '@validator' causes runtime errors.
Forgetting to specify the field name in the decorator.
3fill in blank
hard

Fix the error in the validator method to correctly raise an exception when validation fails.

FastAPI
from pydantic import BaseModel, validator

class Product(BaseModel):
    price: float

    @validator('price')
    def price_must_be_positive(cls, v):
        if v <= 0:
            raise [1]('Price must be positive')
        return v
Drag options to blanks, or click blank then click option'
AException
BRuntimeError
CValueError
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Raising generic Exception does not provide clear validation error.
Using TypeError is incorrect because the type is correct but the value is invalid.
4fill in blank
hard

Fill both blanks to create a validator that checks the 'email' field is lowercase and contains '@'.

FastAPI
class Contact(BaseModel):
    email: str

    @[1]('email')
    def email_must_be_valid(cls, v):
        if '@' not in v or v != v.[2]():
            raise ValueError('Email must be lowercase and contain @')
        return v
Drag options to blanks, or click blank then click option'
Avalidator
Bvalidate
Clower
Dupper
Attempts:
3 left
💡 Hint
Common Mistakes
Using '@validate' instead of '@validator' causes errors.
Using 'upper' instead of 'lower' reverses the logic.
5fill in blank
hard

Fill all three blanks to create a validator that ensures 'age' is an integer and at least 18.

FastAPI
class Person(BaseModel):
    age: int

    @[1]('age')
    def age_must_be_adult(cls, v):
        if not isinstance(v, [2]) or v < [3]:
            raise ValueError('Age must be an integer and at least 18')
        return v
Drag options to blanks, or click blank then click option'
Avalidator
Bint
C18
Dfloat
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'float' instead of 'int' in isinstance check.
Using a wrong minimum age value.