📖 Scenario: You are building a simple API for a bookstore. Each book has a title and an author. The author has a name and an email. You want to organize this data using nested models.
🎯 Goal: Create nested Pydantic models in FastAPI to represent a book and its author. The author model should be nested inside the book model.
📋 What You'll Learn
Create a Pydantic model called Author with fields name (string) and email (string).
Create a Pydantic model called Book with fields title (string) and author (of type Author).
Create a FastAPI app instance called app.
Create a POST endpoint /books/ that accepts a Book model as input.
💡 Why This Matters
🌍 Real World
Nested models help organize complex data structures in APIs, like a book with an author inside it.
💼 Career
Understanding nested models is essential for building clear and maintainable APIs in FastAPI, a popular Python web framework.
Progress0 / 4 steps
1
Create the Author model
Create a Pydantic model called Author with two string fields: name and email.
FastAPI
Hint
Use class Author(BaseModel): and define name and email as string fields.
2
Create the Book model with nested Author
Create a Pydantic model called Book with a string field title and a field author of type Author.
FastAPI
Hint
Define class Book(BaseModel): with title as string and author as type Author.
3
Create the FastAPI app instance
Create a FastAPI app instance called app.
FastAPI
Hint
Write app = FastAPI() to create the app instance.
4
Create POST endpoint to accept Book model
Create a POST endpoint /books/ in app that accepts a Book model as input parameter named book.
FastAPI
Hint
Use @app.post("/books/") decorator and define an async function create_book with parameter book: Book. Return the book object.
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
Step 1: Understand nested models concept
Nested models allow you to include one Pydantic model inside another to represent complex or hierarchical data.
Step 2: Identify the main purpose in FastAPI
FastAPI uses nested models to validate and structure complex JSON data clearly and maintainably.
Final Answer:
To represent complex data structures by embedding one model inside another -> Option A
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
Step 1: Check Pydantic model syntax
Models must inherit from BaseModel and use type annotations for fields.
Step 2: Verify nested model usage
Nested models are declared by using the nested model class as a type annotation for a field.
Final Answer:
class Address(BaseModel): street: str; class User(BaseModel): name: str; address: Address -> Option B
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
Step 1: Understand nested model instantiation
FastAPI/Pydantic automatically converts nested dicts to model instances when creating the parent model.
Step 2: Access nested attribute
Accessing item.price returns the float value 12.5 from the nested Item model.
Final Answer:
12.5 -> Option D
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
Step 1: Check field type annotations
All Pydantic model fields require type annotations (: Type) for proper validation, especially for nested models.
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.
Final Answer:
Missing type annotation for profile field -> Option A
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
Step 1: Use EmailStr for email validation
Pydantic provides EmailStr type to validate email addresses automatically.
Step 2: Define nested models correctly
Author model uses EmailStr, Post model nests Author as a field with correct type annotation.
Final Answer:
class Author(BaseModel): name: str; email: EmailStr
class Post(BaseModel): title: str; content: str; author: Author -> Option C
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 unknownstrongwhile earning +1 Grip toward your certificate.