Bird
Raised Fist0
FastAPIframework~20 mins

Pydantic model basics in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pydantic Model Master
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

class User(BaseModel):
    name: str
    age: int = 18

input_data = {'name': 'Alice'}
user = User(**input_data)
print(user.age)
ARaises ValidationError
BNone
C0
D18
Attempts:
2 left
💡 Hint
Check the default value assigned to the age field in the model.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a Pydantic model with an optional string field?
Select the code snippet that correctly defines a Pydantic model with an optional nickname field of type string.
A
from typing import Optional
from pydantic import BaseModel

class User(BaseModel):
    nickname: str | None = None
B
from pydantic import BaseModel

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

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

class User(BaseModel):
    nickname: str = None
Attempts:
2 left
💡 Hint
Use the typing module's Optional type and assign None as default.
❓ state_output
advanced
2:00remaining
What error does this Pydantic model raise on invalid input?
Given the model and input below, what error will be raised when creating the model instance?
FastAPI
from pydantic import BaseModel

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

input_data = {'id': 'abc', 'price': 10.5}
product = Product(**input_data)
ATypeError
Bpydantic.ValidationError
CValueError
DNo error, instance created successfully
Attempts:
2 left
💡 Hint
Check the type of the 'id' field and the input value provided.
🧠 Conceptual
advanced
2:00remaining
How does Pydantic handle extra fields by default?
If you pass extra fields not defined in the Pydantic model, what happens by default?
APydantic raises a ValidationError for extra fields
BExtra fields are ignored and not included in the model instance
CExtra fields are included as attributes in the model instance
DExtra fields overwrite existing model fields
Attempts:
2 left
💡 Hint
Think about Pydantic's strictness with unexpected data.
🔧 Debug
expert
3:00remaining
Why does this Pydantic model fail to parse nested data correctly?
Examine the code below. Why does Order fail to parse the nested Item data correctly?
FastAPI
from pydantic import BaseModel

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

class Order(BaseModel):
    item: Item

input_data = {'item': {'name': 'Book', 'quantity': '3'}}
order = Order(**input_data)
print(order.item.quantity, type(order.item.quantity))
APydantic converts 'quantity' string '3' to int 3, so no failure occurs
BPydantic raises ValidationError because 'quantity' is a string, not int
CThe nested model is missing a Config class to allow parsing
DThe input data keys must be uppercase to match model fields
Attempts:
2 left
💡 Hint
Pydantic automatically converts compatible types during validation.

Practice

(1/5)
1. What is the main purpose of a Pydantic model in FastAPI?
easy
A. To validate and organize data automatically
B. To create HTML templates
C. To manage database connections
D. To handle user authentication

Solution

  1. Step 1: Understand Pydantic model role

    Pydantic models are designed to check and organize data by validating types and structure. This matches "To validate and organize data automatically".
  2. Final Answer:

    To validate and organize data automatically -> Option A
  3. Quick Check:

    Pydantic = Data validation and organization [OK]
Hint: Pydantic models are for data validation, not UI or DB [OK]
Common Mistakes:
  • Confusing Pydantic with template engines
  • Thinking Pydantic manages databases
  • Assuming Pydantic handles authentication
2. Which of the following is the correct way to define a simple Pydantic model with a required string field name?
easy
A. class User: name = str
B. def User(): name: str
C. class User(BaseModel): name: str
D. class User(BaseModel): name = 'str'

Solution

  1. Step 1: Recall Pydantic model syntax

    A Pydantic model must inherit from BaseModel and define fields with type annotations like class User(BaseModel): name: str. Other options miss inheritance or use assignment instead of type annotation.
  2. Final Answer:

    class User(BaseModel):\n name: str -> Option C
  3. Quick Check:

    BaseModel + type annotation = correct model [OK]
Hint: Use BaseModel and type annotations for fields [OK]
Common Mistakes:
  • Not inheriting from BaseModel
  • Using assignment instead of type annotation
  • Defining model as a function
3. Given this Pydantic model and code:
from pydantic import BaseModel

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

item = Item(id='10', name='Book')
print(item.id, type(item.id))

What will be the output?
medium
A. 10
B. '10'
C. Error: id must be int
D. 10

Solution

  1. Step 1: Understand Pydantic type coercion

    Pydantic automatically converts compatible types like string '10' to int 10, so print(item.id, type(item.id)) outputs 10 <class 'int'>.
  2. Final Answer:

    10 <class 'int'> -> Option D
  3. Quick Check:

    Pydantic converts compatible types automatically [OK]
Hint: Pydantic converts strings to int if possible [OK]
Common Mistakes:
  • Expecting a type error for string input
  • Assuming no conversion happens
  • Confusing output type with input type
4. What is wrong with this Pydantic model definition?
from pydantic import BaseModel

class Product(BaseModel):
    price: float = 'free'
medium
A. Class name should be lowercase
B. Default value 'free' is a string, but price expects a float
C. Missing import for BaseModel
D. Field price must be an integer

Solution

  1. Step 1: Check field type and default value

    price: float = 'free' is invalid because the string 'free' cannot be converted to float, causing a validation error.
  2. Final Answer:

    Default value 'free' is a string, but price expects a float -> Option B
  3. Quick Check:

    Field type and default must match [OK]
Hint: Default values must match field types exactly [OK]
Common Mistakes:
  • Using wrong default value types
  • Ignoring type mismatch errors
  • Thinking class names must be lowercase
5. You want to create a Pydantic model User with an optional age field that defaults to 18 if not provided. Which is the correct way?
hard
A. class User(BaseModel): age: int = 18
B. class User(BaseModel): age: Optional[int]
C. class User(BaseModel): age: int = None
D. class User(BaseModel): age: int

Solution

  1. Step 1: Understand optional field with default

    To make age optional with default 18, use age: int = 18. age: Optional[int] lacks default (required but allows None), age: int = None is invalid (None not int), age: int requires a value.
  2. Final Answer:

    class User(BaseModel):\n age: int = 18 -> Option A
  3. Quick Check:

    Default value makes field optional [OK]
Hint: Assign default value to make field optional [OK]
Common Mistakes:
  • Using Optional without default
  • Assigning None to non-optional int
  • Forgetting to assign default value
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