Model inheritance helps you reuse and organize data models by building new models from existing ones. It keeps your code simple and avoids repetition.
0
0
Model inheritance in FastAPI
Introduction
When you have several data models that share common fields.
When you want to extend a base model with extra information for specific cases.
When you want to create a clear structure for your data models in an API.
When you want to validate similar data with small differences.
When you want to keep your code clean and easy to maintain.
Syntax
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.
Examples
Dog inherits the name field from Animal and adds breed.
FastAPI
from pydantic import BaseModel class Animal(BaseModel): name: str class Dog(Animal): breed: str
Employee has all Person fields plus employee_id.
FastAPI
from pydantic import BaseModel class Person(BaseModel): first_name: str last_name: str class Employee(Person): employee_id: int
Sample Program
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.
FastAPI
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)
OutputSuccess
Important Notes
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.
Summary
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.