Bird
Raised Fist0
FastAPIframework~10 mins

Custom validation with validator decorator in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom validation with validator decorator
Define Pydantic Model
↓
Add @validator Decorator
↓
Write Validation Function
↓
Create Model Instance
↓
Trigger Validation
↓
Accept
This flow shows how a Pydantic model uses a @validator decorator to check data when creating an instance, accepting valid data or raising errors for invalid.
Execution Sample
FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    name: str

    @validator('name')
    def name_must_not_be_empty(cls, v):
        if not v.strip():
            raise ValueError('Name cannot be empty')
        return v
Defines a User model with a custom validator to ensure the name is not empty or just spaces.
Execution Table
StepActionInput ValueValidation CheckResult
1Create User with name='Alice''Alice'Check if name is emptyPass, name='Alice' accepted
2Create User with name=' '' 'Check if name is emptyFail, raises ValueError 'Name cannot be empty'
3Create User with name='Bob''Bob'Check if name is emptyPass, name='Bob' accepted
4Create User with name=''''Check if name is emptyFail, raises ValueError 'Name cannot be empty'
💡 Validation stops on first failure; valid names pass through.
Variable Tracker
VariableStartAfter 1After 2After 3After 4
nameundefined'Alice'' ''Bob'''
Key Moments - 2 Insights
Why does the validator raise an error when the name is only spaces?
Because the validator uses v.strip() to remove spaces and checks if the result is empty. In execution_table row 2, the input ' ' becomes empty after strip, triggering the error.
What happens if the validator returns the value without raising an error?
The value passes validation and is accepted as shown in execution_table rows 1 and 3 where valid names are returned.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result when creating a User with name=' '?
APass, name accepted
BPass, but name is trimmed
CFail, raises ValueError 'Name cannot be empty'
DNo validation occurs
💡 Hint
See execution_table row 2 where input ' ' fails validation.
At which step does the validation pass successfully for the name 'Bob'?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Check execution_table row 3 for name='Bob' passing validation.
If the validator did not strip spaces, what would happen for input ' '?
AIt would pass validation
BIt would raise an error
CIt would trim spaces automatically
DIt would convert to None
💡 Hint
Consider how v.strip() affects validation in the code and execution_table row 2.
Concept Snapshot
Use @validator decorator in Pydantic models to add custom checks.
Define a method with cls and value parameters.
Raise ValueError to reject invalid data.
Return the value if valid.
Validation runs when creating model instances.
Full Transcript
This example shows how to add custom validation to a Pydantic model using the @validator decorator. The User model has a name field. The validator method name_must_not_be_empty checks if the name is empty or only spaces by stripping whitespace. If empty, it raises a ValueError with a message. When creating User instances, the validator runs automatically. Valid names like 'Alice' and 'Bob' pass and are accepted. Names that are empty or just spaces cause a validation error. This helps ensure data quality before using the model.

Practice

(1/5)
1. What is the main purpose of using the @validator decorator in a Pydantic model within FastAPI?
easy
A. To define database relationships
B. To automatically generate API routes
C. To add custom validation logic for model fields
D. To format the output JSON response

Solution

  1. Step 1: Understand the role of @validator

    The @validator decorator is used inside Pydantic models to add custom validation logic for fields.
  2. Step 2: Differentiate from other functionalities

    It does not generate routes, define database relations, or format output JSON; those are handled elsewhere.
  3. Final Answer:

    To add custom validation logic for model fields -> Option C
  4. Quick Check:

    Custom validation = To add custom validation logic for model fields [OK]
Hint: Remember: @validator checks field values before use [OK]
Common Mistakes:
  • Confusing validation with route creation
  • Thinking it formats output JSON
  • Assuming it manages database relations
2. Which of the following is the correct syntax to create a validator for the field email in a Pydantic model?
easy
A. @validator['email']\ndef check_email(cls, value):\n return value
B. @validate('email')\ndef check_email(cls, value):\n return value
C. @validator(email)\ndef check_email(cls, value):\n return value
D. @validator('email')\ndef check_email(cls, value):\n return value

Solution

  1. Step 1: Identify correct decorator usage

    The correct decorator is @validator('field_name') with the field name as a string.
  2. Step 2: Check syntax correctness

    @validator('email')\ndef check_email(cls, value):\n return value uses @validator('email') correctly; others use wrong decorator names or syntax.
  3. Final Answer:

    @validator('email')\ndef check_email(cls, value):\n return value -> Option D
  4. Quick Check:

    Correct decorator syntax = @validator('email')\ndef check_email(cls, value):\n return value [OK]
Hint: Use quotes around field name in @validator [OK]
Common Mistakes:
  • Omitting quotes around field name
  • Using wrong decorator name like @validate
  • Using brackets [] instead of parentheses ()
3. Given the following Pydantic model, what will happen if you create an instance with age=15?
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)
medium
A. A ValueError is raised with message 'Must be at least 18'
B. The user instance is created with age 15
C. The age is automatically set to 18
D. A TypeError is raised because age is int

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: Apply input value to validator

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

    A ValueError is raised with message 'Must be at least 18' -> Option A
  4. Quick Check:

    Age < 18 triggers ValueError = A ValueError is raised with message 'Must be at least 18' [OK]
Hint: Validator raises error if condition fails [OK]
Common Mistakes:
  • Assuming instance is created despite validation error
  • Thinking age auto-corrects to 18
  • Confusing ValueError with TypeError
4. Identify the error in this validator code snippet:
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 decorator should be @validate
B. Missing cls parameter in validator method
C. Return statement is missing
D. Field name in decorator should be price without quotes

Solution

  1. Step 1: Check validator method signature

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

    The method only has value, missing cls, causing a TypeError.
  3. Final Answer:

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

    Validator method needs cls first = Missing cls parameter in validator method [OK]
Hint: Validator methods always start with cls, then value [OK]
Common Mistakes:
  • Omitting cls parameter
  • Using wrong decorator name
  • Forgetting to return the value
5. You want to create a Pydantic model that validates a username field to ensure it is at least 3 characters long and contains only letters and numbers. Which validator implementation correctly achieves this?
hard
A. from pydantic import BaseModel, validator import re class User(BaseModel): username: str @validator('username') def valid_username(cls, v): if len(v) < 3 or not re.match(r'^[a-zA-Z0-9]+$', v): raise ValueError('Username must be 3+ chars and alphanumeric') return v
B. from pydantic import BaseModel, validator class User(BaseModel): username: str @validator('username') def valid_username(cls, v): if len(v) > 3 and v.isalnum(): raise ValueError('Username must be 3+ chars and alphanumeric') return v
C. from pydantic import BaseModel, validator class User(BaseModel): username: str @validator('username') def valid_username(cls, v): if len(v) < 3 or not v.isalpha(): raise ValueError('Username must be 3+ chars and letters only') return v
D. from pydantic import BaseModel, validator import re class User(BaseModel): username: str @validator('username') def valid_username(cls, v): if len(v) < 3 or not re.match(r'^[a-z]+$', v): raise ValueError('Username must be 3+ chars and lowercase letters only') return v

Solution

  1. Step 1: Check length and character conditions

    The username must be at least 3 characters and only letters or numbers.
  2. Step 2: Evaluate each option's validation logic

    from pydantic import BaseModel, validator import re class User(BaseModel): username: str @validator('username') def valid_username(cls, v): if len(v) < 3 or not re.match(r'^[a-zA-Z0-9]+$', v): raise ValueError('Username must be 3+ chars and alphanumeric') return v correctly checks length & uses regex to allow letters and numbers only. Others either check wrong conditions or restrict letters only.
  3. Final Answer:

    Option A correctly validates username length and alphanumeric characters -> Option A
  4. Quick Check:

    Length >=3 and alphanumeric = from pydantic import BaseModel, validator import re class User(BaseModel): username: str @validator('username') def valid_username(cls, v): if len(v) < 3 or not re.match(r'^[a-zA-Z0-9]+$', v): raise ValueError('Username must be 3+ chars and alphanumeric') return v [OK]
Hint: Use regex to check alphanumeric and length together [OK]
Common Mistakes:
  • Using isalpha() instead of isalnum()
  • Checking length incorrectly (greater than vs less than)
  • Restricting to letters only when numbers allowed
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