DTO & Mapper Pattern
Data Transfer Object (DTO) and Mapper patterns for decoupling layers, controlling API contracts, and safely transforming data between boundaries.
- Difficulty
- intermediate
- Read time
- 1 min read
- Version
- v1.0.0
- Confidence
- established
- Last updated
Quick Reference
DTO Pattern: Separate DTOs for input/output/internal. Use Zod schemas in TypeScript (infer types). Use Pydantic models in Python (from_attributes=True for ORM). Never expose domain/DB models directly. Base model inheritance to reduce duplication. Mapper functions or class methods for transformation.
Use When
- Building API contracts
- Separating layers in clean architecture
- Hiding internal implementation
- Validating external input
Skip When
- Simple scripts without layers
- Internal-only data structures
DTO & Mapper Pattern
Data Transfer Object (DTO) and Mapper patterns for decoupling layers, controlling API contracts, and safely transforming data between boundaries.