Model inheritance helps you reuse and organize data models by building new models from existing ones. It keeps your code simple and avoids repetition.
Model inheritance in FastAPI
from pydantic import BaseModel class BaseUser(BaseModel): username: str email: str class UserInDB(BaseUser): hashed_password: str
Use normal Python class inheritance to extend models.
Child models inherit all fields and validation from parent models.
from pydantic import BaseModel class Animal(BaseModel): name: str class Dog(Animal): breed: str
from pydantic import BaseModel class Person(BaseModel): first_name: str last_name: str class Employee(Person): employee_id: int
This example shows how to use model inheritance in FastAPI. UserCreate adds a password field to the base user model. The endpoint accepts UserCreate and returns a User with an id.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class UserBase(BaseModel): username: str email: str class UserCreate(UserBase): password: str class User(UserBase): id: int @app.post('/users/') async def create_user(user: UserCreate): # Imagine saving user and returning user with id return User(id=1, username=user.username, email=user.email)
Model inheritance works because Pydantic models are normal Python classes.
Inherited models keep validation rules from parent models.
You can override fields or add new ones in child models.
Model inheritance helps reuse fields and validation in FastAPI data models.
Use it to keep your code clean and avoid repeating fields.
Child models extend parent models with new fields or changes.
Practice
Solution
Step 1: Understand model inheritance concept
Model inheritance allows child models to reuse fields and validation from a parent model, avoiding repetition.Step 2: Identify the purpose in FastAPI context
FastAPI uses Pydantic models where inheritance helps keep code clean by extending existing models.Final Answer:
To reuse fields and validation rules from a parent model in child models -> Option AQuick Check:
Model inheritance = reuse fields and validation [OK]
- Thinking inheritance creates database tables automatically
- Confusing model inheritance with HTTP request handling
- Believing inheritance creates unrelated models
Solution
Step 1: Recall Python class inheritance syntax
In Python, inheritance is done by placing the parent class name in parentheses after the child class name.Step 2: Match with FastAPI model inheritance
FastAPI uses Pydantic models which follow Python syntax, soclass ChildModel(ParentModel): passis correct.Final Answer:
class ChildModel(ParentModel): pass -> Option CQuick Check:
Python inheritance syntax = parentheses [OK]
- Using 'extends' like in JavaScript or Java
- Using 'inherits' keyword which doesn't exist in Python
- Using colon without parentheses for inheritance
ChildModel have?from pydantic import BaseModel
class ParentModel(BaseModel):
id: int
name: str
class ChildModel(ParentModel):
age: int
Solution
Step 1: Identify fields in ParentModel
ParentModel has fieldsidandname.Step 2: Identify fields added in ChildModel
ChildModel inherits ParentModel and addsage.Final Answer:
id, name, age -> Option BQuick Check:
ChildModel fields = parent fields + new fields [OK]
- Ignoring inherited fields from parent
- Assuming child model only has new fields
- Confusing field names or missing fields
from pydantic import BaseModel
class ParentModel(BaseModel):
id: int
class ChildModel(ParentModel):
id: str
Solution
Step 1: Check field types in parent and child
ParentModel hasidasint, ChildModel overridesidasstr.Step 2: Understand Pydantic field overriding rules
Pydantic allows overriding the type of an inherited field; the child's definition takes precedence.Final Answer:
ChildModel can override a field with a different type -> Option DQuick Check:
Field type override allowed [OK]
- Thinking child cannot change field types
- Confusing inheritance direction
- Believing BaseModel cannot be inherited
UserUpdate model that inherits from UserBase but makes all fields optional for partial updates. Which approach correctly uses model inheritance in FastAPI?Solution
Step 1: Understand the goal of partial updates
Partial updates require fields to be optional so they can be omitted.Step 2: Use inheritance and make fields optional
Inheriting fromUserBaseand redefining fields asOptionalwith defaultNoneallows partial updates.Final Answer:
class UserUpdate(UserBase): id: Optional[int] = None name: Optional[str] = None -> Option AQuick Check:
Make fields optional in child model for partial updates [OK]
- Leaving fields required in update model
- Not inheriting from base model
- Copying fields without making them optional
Ready to prove it?
Pass the test and this pattern moves unknown
