Bird
Raised Fist0
FastAPIframework~20 mins

Pydantic model definition in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pydantic Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Pydantic model validation?
Given the Pydantic model and input data below, what will be the value of user.age after validation?
FastAPI
from pydantic import BaseModel, Field

class User(BaseModel):
    name: str
    age: int = Field(default=18, ge=0, le=120)

user = User(name='Alice', age=25)
ARaises a ValidationError
B18
CNone
D25
Attempts:
2 left
💡 Hint
Check the value passed to the model and the default value.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a Pydantic model with an optional email field?
Select the code snippet that correctly defines a Pydantic model with an optional email field of type str.
A
from pydantic import BaseModel

class User(BaseModel):
    email: str = Optional[None]
B
from pydantic import BaseModel

class User(BaseModel):
    email: str | None = None
C
from pydantic import BaseModel
from typing import Optional

class User(BaseModel):
    email: Optional[str] = None
D
from pydantic import BaseModel
from typing import Optional

class User(BaseModel):
    email: str = Optional[str]
Attempts:
2 left
💡 Hint
Use the correct typing for optional fields and default values.
🔧 Debug
advanced
2:00remaining
What error does this Pydantic model raise when instantiated?
Consider this model and instantiation code. What error will occur?
FastAPI
from pydantic import BaseModel

class Product(BaseModel):
    id: int
    price: float

product = Product(id='abc', price=19.99)
ATypeError: id must be int
BValidationError: id must be an integer
CNo error, product created successfully
DValueError: price must be float
Attempts:
2 left
💡 Hint
Check the type of the id field and the value passed.
❓ state_output
advanced
2:00remaining
What is the output of this Pydantic model with a computed property?
Given the model below, what will item.total_price output?
FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    quantity: int
    price_per_unit: float

    @property
    def total_price(self) -> float:
        return self.quantity * self.price_per_unit

item = Item(name='Pen', quantity=3, price_per_unit=1.5)
print(item.total_price)
A4.5
B3
C1.5
DRaises AttributeError
Attempts:
2 left
💡 Hint
Multiply quantity by price_per_unit.
🧠 Conceptual
expert
3:00remaining
Which option best describes Pydantic's model validation behavior on nested models?
Consider a Pydantic model with a nested model field. Which statement is true about how Pydantic validates nested models?
APydantic validates nested models recursively, applying all field validations in nested models automatically.
BPydantic only validates the top-level model and ignores nested models unless explicitly validated.
CValidation of nested models requires manual calls to their <code>validate()</code> method.
DNested models are treated as plain dictionaries without validation.
Attempts:
2 left
💡 Hint
Think about how Pydantic handles complex data structures.

Practice

(1/5)
1. What is the main purpose of defining a Pydantic model in FastAPI?
easy
A. To specify the expected data structure and validate incoming data automatically
B. To create database tables automatically
C. To style the API responses with CSS
D. To handle user authentication

Solution

  1. Step 1: Understand Pydantic model role

    Pydantic models define the shape and types of data expected in requests or responses.
  2. Step 2: Identify validation feature

    They automatically check if incoming data matches the defined types and structure.
  3. Final Answer:

    To specify the expected data structure and validate incoming data automatically -> Option A
  4. Quick Check:

    Data validation = C [OK]
Hint: Pydantic models shape and check data automatically [OK]
Common Mistakes:
  • Confusing Pydantic models with database models
  • Thinking Pydantic handles styling or authentication
  • Assuming Pydantic models run code logic
2. Which of the following is the correct way to define a Pydantic model with a required string field name and an optional integer field age?
easy
A. class User(BaseModel): name: str; age: int = None
B. class User(BaseModel): name: str; age: Optional[int] = None
C. class User(BaseModel): name = str; age = int = None
D. class User(BaseModel): name: str = None; age: int

Solution

  1. Step 1: Check required and optional fields syntax

    Required fields have type only, optional fields use Optional[type] with default None.
  2. Step 2: Identify correct syntax

    class User(BaseModel): name: str; age: Optional[int] = None uses name: str (required) and age: Optional[int] = None (optional), which is correct.
  3. Final Answer:

    class User(BaseModel): name: str; age: Optional[int] = None -> Option B
  4. Quick Check:

    Optional fields use Optional[type] = None [OK]
Hint: Use Optional[type] = None for optional fields [OK]
Common Mistakes:
  • Using plain type with default None without Optional
  • Assigning type with equals sign incorrectly
  • Setting required fields with default None
3. Given this Pydantic model:
from pydantic import BaseModel

class Item(BaseModel):
    id: int
    name: str
    price: float

item = Item(id='5', name='Book', price=12.99)

What will be the type of item.id after creation?
medium
A. TypeError raised
B. str with value '5'
C. float with value 5.0
D. int with value 5

Solution

  1. Step 1: Understand Pydantic type coercion

    Pydantic automatically converts compatible types to the declared type if possible.
  2. Step 2: Analyze input and conversion

    The string '5' can be converted to int 5, so item.id becomes int 5.
  3. Final Answer:

    int with value 5 -> Option D
  4. Quick Check:

    Pydantic converts compatible types automatically [OK]
Hint: Pydantic converts strings to int if possible [OK]
Common Mistakes:
  • Assuming input type must match exactly without conversion
  • Expecting a TypeError for string input
  • Thinking the value stays as string
4. What is wrong with this Pydantic model definition?
from pydantic import BaseModel

class Product(BaseModel):
    name: str
    price: float = 'free'
medium
A. Missing import for Optional
B. Class must inherit from object, not BaseModel
C. Default value 'free' is a string but price expects a float
D. Field names cannot be lowercase

Solution

  1. Step 1: Check field types and default values

    The field price expects a float but is given a string default 'free'.
  2. Step 2: Understand Pydantic validation

    Pydantic will raise a validation error because 'free' cannot be converted to float.
  3. Final Answer:

    Default value 'free' is a string but price expects a float -> Option C
  4. Quick Check:

    Default value type must match field type [OK]
Hint: Default values must match declared field types [OK]
Common Mistakes:
  • Assigning default values of wrong type
  • Confusing inheritance requirements
  • Thinking field names have naming restrictions
5. You want to create a Pydantic model User with a required username (string), an optional email (string), and a roles list of strings that defaults to an empty list. Which is the correct way to define it?
hard
A. class User(BaseModel): username: str; email: Optional[str] = None; roles: list[str] = Field(default_factory=list)
B. class User(BaseModel): username: str; email: str = None; roles: list[str] = []
C. class User(BaseModel): username: str; email: Optional[str]; roles: list[str] = None
D. class User(BaseModel): username: str; email: Optional[str] = None; roles: list[str] = []

Solution

  1. Step 1: Identify optional email field syntax

    Email is optional, so use Optional[str] = None to allow missing value.
  2. Step 2: Handle mutable default for roles list

    Using roles: list[str] = [] is unsafe because lists are mutable defaults shared across instances. Use Field(default_factory=list) to create a new list each time.
  3. Final Answer:

    class User(BaseModel): username: str; email: Optional[str] = None; roles: list[str] = Field(default_factory=list) -> Option A
  4. Quick Check:

    Use Field(default_factory=list) for mutable defaults [OK]
Hint: Use Field(default_factory=list) for empty list defaults [OK]
Common Mistakes:
  • Using mutable empty list as default directly
  • Not marking optional fields with Optional and default None
  • Assigning None to non-optional list fields
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