Skip to main content
As your API grows, you’ll need multiple related models for different purposes. FastAPI and Pydantic make it easy to work with model inheritance, unions, and composition.

The Problem: Multiple Models Needed

For a single resource (like a user), you often need different models:
  • Input model: Accepts user data including passwords
  • Output model: Returns data without sensitive information
  • Database model: Includes internal fields like hashed passwords
Never return sensitive data like passwords in API responses, even if hashed.

Model Inheritance

Use Pydantic model inheritance to reduce duplication:
1

UserBase

Contains common fields shared across all models
2

UserIn

Adds password field for accepting input
3

UserOut

Uses only base fields for secure output
4

UserInDB

Adds hashed_password for database storage

Union Types for Multiple Response Models

Return different models based on conditions:
FastAPI will automatically match the response to the correct model based on the data structure.

List of Models

Return lists of model instances:

Dict Response Model

Return arbitrary dict responses:
While dict[str, float] provides type hints, it doesn’t offer field-level validation like Pydantic models.

Model Composition

Compose models by including other models as fields:

Nested Model Example

Deeply Nested Models

You can nest models as deeply as needed:
FastAPI will validate the entire nested structure automatically, providing detailed error messages for any validation failures.

Generic Models with Type Variables

Create generic response wrappers:

Model Config and Settings

Customize model behavior with configuration:

When to Use Multiple Models

1

Security

Separate input/output models to exclude sensitive data
2

API Versions

Different models for different API versions
3

User Roles

Different response models based on user permissions
4

Resource States

Different models for resource creation vs retrieval

Best Practices

Avoid duplicating field definitions. Use inheritance or composition instead.