Bird
Raised Fist0
FastAPIframework~20 mins

Nested models in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Nested Models 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 FastAPI nested model response?
Given the following FastAPI models and endpoint, what JSON response will the client receive when requesting /user/1?
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Address(BaseModel):
    street: str
    city: str

class User(BaseModel):
    id: int
    name: str
    address: Address

@app.get('/user/{user_id}', response_model=User)
async def get_user(user_id: int):
    return {
        'id': user_id,
        'name': 'Alice',
        'address': {
            'street': '123 Main St',
            'city': 'Wonderland'
        }
    }
A{"id": 1, "name": "Alice", "address": {"street": "123 Main St", "city": "Wonderland"}}
B{"id": 1, "name": "Alice", "address": "123 Main St, Wonderland"}
C{"id": 1, "name": "Alice", "address": {"street": "123 Main St"}}
D{"id": 1, "name": "Alice"}
Attempts:
2 left
💡 Hint
Think about how nested Pydantic models serialize data in FastAPI responses.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines nested Pydantic models in FastAPI?
You want to define a nested model where Order contains a list of Item models. Which code snippet correctly defines this?
A
class Item(BaseModel):
    name: str
    price: float

class Order(BaseModel):
    id: int
    items: Item[]
B
class Item(BaseModel):
    name: str
    price: float

class Order(BaseModel):
    id: int
    items: list[Item]
C
class Item(BaseModel):
    name: str
    price: float

class Order(BaseModel):
    id: int
    items: List[Item]
D
class Item(BaseModel):
    name: str
    price: float

class Order(BaseModel):
    id: int
    items: dict[Item]
Attempts:
2 left
💡 Hint
Use Python 3.9+ built-in generic types for lists.
🔧 Debug
advanced
2:00remaining
Why does this nested model validation fail in FastAPI?
Consider these models and endpoint:
class Profile(BaseModel):
    age: int
    bio: str

class User(BaseModel):
    username: str
    profile: Profile

@app.post('/users')
async def create_user(user: User):
    return user
If the client sends {"username": "bob", "profile": {"age": "twenty", "bio": "Hi"}}, what error occurs and why?
ATypeError because 'profile' is missing required fields
BKeyError because 'bio' key is missing
CNo error, the data is accepted as is
DValidationError because 'age' expects an int but received a string 'twenty'
Attempts:
2 left
💡 Hint
Check the data types expected by Pydantic models.
❓ state_output
advanced
2:00remaining
What is the value of user.address.city after this code runs?
Given these Pydantic models and code snippet, what is the value of user.address.city?
class Address(BaseModel):
    street: str
    city: str

class User(BaseModel):
    name: str
    address: Address

user = User(name='Eve', address={'street': '1st Ave', 'city': 'Metropolis'})
ANone
B"1st Ave"
C"Metropolis"
DRaises AttributeError
Attempts:
2 left
💡 Hint
Pydantic converts nested dicts into model instances automatically.
🧠 Conceptual
expert
2:00remaining
Which statement about nested Pydantic models in FastAPI is TRUE?
Select the one true statement about nested models in FastAPI using Pydantic.
APydantic automatically converts nested dictionaries into nested model instances during validation.
BNested models must always be declared with the <code>Field()</code> function to work correctly.
CFastAPI requires manual serialization of nested models before returning them in responses.
DYou cannot use lists of nested models in FastAPI request or response models.
Attempts:
2 left
💡 Hint
Think about how Pydantic handles nested data structures.

Practice

(1/5)
1. What is the main purpose of using nested models in FastAPI?
easy
A. To represent complex data structures by embedding one model inside another
B. To speed up the API response time
C. To automatically generate HTML pages
D. To replace database models with simpler ones

Solution

  1. Step 1: Understand nested models concept

    Nested models allow you to include one Pydantic model inside another to represent complex or hierarchical data.
  2. Step 2: Identify the main purpose in FastAPI

    FastAPI uses nested models to validate and structure complex JSON data clearly and maintainably.
  3. Final Answer:

    To represent complex data structures by embedding one model inside another -> Option A
  4. Quick Check:

    Nested models = complex data representation [OK]
Hint: Nested models = models inside models for complex data [OK]
Common Mistakes:
  • Thinking nested models improve speed
  • Confusing nested models with HTML generation
  • Assuming nested models replace databases
2. Which of the following is the correct way to define a nested model in FastAPI using Pydantic?
easy
A. class User(BaseModel): name: str; address: str
B. class Address(BaseModel): street: str; class User(BaseModel): name: str; address: Address
C. class User(BaseModel): name: str; address = Address()
D. class Address: street: str; class User: name: str; address: Address

Solution

  1. Step 1: Check Pydantic model syntax

    Models must inherit from BaseModel and use type annotations for fields.
  2. Step 2: Verify nested model usage

    Nested models are declared by using the nested model class as a type annotation for a field.
  3. Final Answer:

    class Address(BaseModel): street: str; class User(BaseModel): name: str; address: Address -> Option B
  4. Quick Check:

    Nested model as type annotation = correct syntax [OK]
Hint: Use nested model class as field type with BaseModel inheritance [OK]
Common Mistakes:
  • Not inheriting from BaseModel
  • Assigning nested model instance instead of type
  • Using plain classes without BaseModel
3. Given the following FastAPI models:
class Item(BaseModel): name: str; price: float
class Order(BaseModel): id: int; item: Item

What will be the output of Order(id=1, item={'name': 'Book', 'price': 12.5}).item.price?
medium
A. None
B. '12.5'
C. Error: item must be an Item instance
D. 12.5

Solution

  1. Step 1: Understand nested model instantiation

    FastAPI/Pydantic automatically converts nested dicts to model instances when creating the parent model.
  2. Step 2: Access nested attribute

    Accessing item.price returns the float value 12.5 from the nested Item model.
  3. Final Answer:

    12.5 -> Option D
  4. Quick Check:

    Nested dict converts to model, attribute accessed = 12.5 [OK]
Hint: Nested dicts auto-convert to models, access attributes normally [OK]
Common Mistakes:
  • Expecting string instead of float
  • Thinking nested dicts cause errors
  • Assuming nested model must be instance, not dict
4. Identify the error in this FastAPI nested model code:
class Profile(BaseModel): age: int
class User(BaseModel): username: str; profile = {"age": 30}
medium
A. Missing type annotation for profile field
B. Profile class must inherit from BaseSettings, not BaseModel
C. Default value for nested model must be a Profile instance, not a dict
D. username field should be Optional[str]

Solution

  1. Step 1: Check field type annotations

    All Pydantic model fields require type annotations (: Type) for proper validation, especially for nested models.
  2. Step 2: Identify the missing annotation

    The profile field lacks type annotation: it should be profile: Profile = {"age": 30} or profile: Profile = Profile(age=30) to enable nested model validation.
  3. Final Answer:

    Missing type annotation for profile field -> Option A
  4. Quick Check:

    Type annotation required for nested model fields [OK]
Hint: All model fields must have type annotations: field: Type [OK]
Common Mistakes:
  • Using dict instead of model instance as default
  • Ignoring type annotations
  • Confusing BaseModel with BaseSettings
5. You want to create a FastAPI model for a blog post with nested author info. The author has name and email. The post has title, content, and author. Which code correctly defines these nested models and validates that the author's email is a valid email address?
hard
A. class Author(BaseModel): name: str; email: str class Post(BaseModel): title: str; content: str; author: Author @validator('email') def check_email(cls, v): return v
B. class Author(BaseModel): name: str; email: str class Post(BaseModel): title: str; content: str; author: dict
C. class Author(BaseModel): name: str; email: EmailStr class Post(BaseModel): title: str; content: str; author: Author
D. class Author(BaseModel): name: str; email: EmailStr class Post(BaseModel): title: str; content: str; author: dict

Solution

  1. Step 1: Use EmailStr for email validation

    Pydantic provides EmailStr type to validate email addresses automatically.
  2. Step 2: Define nested models correctly

    Author model uses EmailStr, Post model nests Author as a field with correct type annotation.
  3. Final Answer:

    class Author(BaseModel): name: str; email: EmailStr class Post(BaseModel): title: str; content: str; author: Author -> Option C
  4. Quick Check:

    EmailStr + nested Author model = correct validation [OK]
Hint: Use EmailStr type and nested model as field type [OK]
Common Mistakes:
  • Using plain str for email without validation
  • Setting author field as dict instead of Author model
  • Trying to validate email with incorrect validator placement
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