0
0
FastAPIframework~10 mins

Custom validators 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 BaseModel class from Pydantic.

FastAPI
from pydantic import [1]

class User([1]):
    name: str
Drag options to blanks, or click blank then click option'
AField
BBaseModel
Cvalidator
DValidationError
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Field instead of BaseModel
Trying to import validator for the model base
2fill in blank
medium

Complete the code to create a custom validator method for the 'age' field.

FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    age: int

    @validator('[1]')
    def check_age(cls, value):
        if value < 18:
            raise ValueError('Must be at least 18')
        return value
Drag options to blanks, or click blank then click option'
Apassword
Bname
Cemail
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different field name in the validator decorator
Forgetting to specify the field name
3fill in blank
hard

Fix the error in the validator method name to correctly validate the 'email' field.

FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    email: str

    @validator('[1]')
    def validate_email(cls, value):
        if '@' not in value:
            raise ValueError('Invalid email')
        return value
Drag options to blanks, or click blank then click option'
Aemail
Bvalidate_email
Ccheck_email
Demail_validator
Attempts:
3 left
💡 Hint
Common Mistakes
Using the method name instead of the field name in the decorator
Using a made-up field name
4fill in blank
hard

Fill both blanks to create a validator that checks the 'password' field length is at least 8 characters.

FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    password: str

    @validator('[1]')
    def [2](cls, value):
        if len(value) < 8:
            raise ValueError('Password too short')
        return value
Drag options to blanks, or click blank then click option'
Apassword
Bcheck_password
Cvalidate_password
Dpassword_validator
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong field name in the decorator
Using an invalid method name
5fill in blank
hard

Fill all three blanks to create a validator that ensures the 'username' field is lowercase and at least 3 characters.

FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    username: str

    @validator('[1]')
    def [2](cls, value):
        if len(value) < [3]:
            raise ValueError('Username too short')
        return value.lower()
Drag options to blanks, or click blank then click option'
Ausername
Bvalidate_username
C3
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong field name in decorator
Setting incorrect minimum length
Using method names that don't match the field