Body - Nested Models
Part of: FastAPI Basics
Master complex nested data structures with FastAPI and Pydantic. Learn to use lists, sets, nested models, and deeply nested structures for powerful APIs.
What You'll Learn
- Create models with list and set fields using proper type annotations
- Build nested models by embedding one Pydantic model inside another
- Handle lists of nested models for complex data structures
- Use Dict fields for key-value mappings with type safety
- Understand deeply nested models and their validation benefits
Theory and Concepts
Body - Nested Models
🎯 What You'll Learn
This lesson covers the complete official FastAPI "Body - Nested Models" tutorial. You'll master creating arbitrarily deeply nested models using FastAPI and Pydantic, enabling you to handle complex data structures with full validation and documentation.
By the end of this lesson, you'll understand how to:
- Create models with list and set fields using proper type annotations
- Build nested models by embedding one Pydantic model inside another
- Handle lists of nested models for complex data structures
- Use Dict fields for key-value mappings with type safety
- Understand deeply nested models and their validation benefits
📚 1. List Fields
You can define an attribute to be a Python list:
[Code Example]
This makes tags a list, but doesn't specify the type of elements inside the list.
🎯 2. List Fields with Type Parameters
Python has a specific way to declare lists with internal types using "type parameters":
Import typing's List
For Python versions before 3.9, import List from the typing module:
[Code Example]
Modern Python (3.9+)
In Python 3.9 and above, you can use the standard list:
[Code Example]
Request body example:
[Code Example]
🔄 3. Set Fields
You can use Set types for collections of unique items:
[Code Example]
Benefits of Sets:
- Automatically removes duplicates
- Validates uniqueness
- More efficient for membership testing
Request body example:
[Code Example]
Result: tags will be {"electronics", "computers"} (duplicate removed)
🏗️ 4. Nested Models
You can define a Pydantic model as the type of an attribute:
[Code Example]
Request body example:
[Code Example]
Special Pydantic Types
- HttpUrl: Validates that the string is a valid HTTP URL
- EmailStr: Validates email addresses (requires email-validator)
- UUID: Validates UUID strings
- datetime: Handles datetime objects
📋 5. Lists of Nested Models
You can have lists containing nested models:
[Code Example]
Request body example:
[Code Example]
🗂️ 6. Deeply Nested Models
You can create arbitrarily deep nesting:
[Code Example]
🗃️ 7. Dict Fields
You can use Dict for key-value mappings:
[Code Example]
Request body example:
[Code Example]
Response:
[Code Example]
🌟 Key Concepts
Type Safety Benefits
Nested models provide:
- Automatic validation at every level
- Type conversion for compatible types
- Clear error messages showing exactly which nested field failed
- IDE support with autocomplete for nested attributes
- Automatic documentation in OpenAPI schema
Validation Flow
1. Top-level validation: Main model fields are validated
2. Nested validation: Each nested model validates its own fields
3. Collection validation: Lists/Sets validate each element
4. Type conversion: Automatic conversion where possible
5. Error aggregation: All validation errors collected and returned
Performance Considerations
- Validation overhead: Deeper nesting = more validation work
- Memory usage: Nested objects use more memory
- Serialization cost: Complex structures take longer to serialize/deserialize
- Network payload: Larger JSON payloads
💡 Best Practices
Model Organization
[Code Example]
Validation Constraints
[Code Example]
Optional vs Required Nesting
[Code Example]
🎯 Complete Example
[Code Example]
🔗 What's Next?
In the next lesson, you'll learn about Extra Data Types, where you'll discover FastAPI's support for additional data types like UUID, datetime, timedelta, frozenset, bytes, and Decimal.
📖 Additional Resources
- FastAPI Official Tutorial - Body - Nested Models
- Pydantic Models Documentation
- Pydantic Field Types
- Python Typing Documentation
Helpful Hint
Use List[str] for typed lists, Set[str] for unique collections, and embed Pydantic models inside other models for complex nested structures.