dataclasses for request and response models. This provides flexibility when working with existing codebases or when you prefer the simplicity of dataclasses.
Basic Dataclass Usage
You can use standard Python dataclasses directly in your FastAPI path operations:- Validate the incoming data
- Serialize responses to JSON
- Generate OpenAPI documentation
- Provide interactive API docs
This works because Pydantic has internal support for standard dataclasses. FastAPI converts them to Pydantic’s own dataclasses under the hood.
Dataclasses vs Pydantic Models
While dataclasses work well with FastAPI, there are important differences to consider:Response Models with Dataclasses
Dataclasses work seamlessly in theresponse_model parameter:
Nested Dataclasses
You can combine dataclasses with type annotations to create nested data structures:For nested dataclasses, you might need to use
field() from the dataclasses module to set default factories for mutable default values like lists and dictionaries.Using Pydantic Dataclasses
If you encounter issues with standard dataclasses (especially with complex nested structures), you can usepydantic.dataclasses as a drop-in replacement:
When to Use Dataclasses
Dataclasses are a good choice when:- Migrating existing code: You have existing dataclasses in your codebase
- Simple data structures: Your models don’t need complex validation
- Familiarity: Your team is more comfortable with standard Python dataclasses
- Simplicity: You prefer the cleaner syntax without inheritance
When to Use Pydantic Models
Choose Pydantic models when you need:- Advanced validation: Field constraints, custom validators, regex patterns
- Computed fields: Fields calculated from other fields
- Custom serialization: Control over JSON serialization behavior
- ORM integration: Working with databases and SQLAlchemy
- Better performance: Optimized JSON serialization with Rust core
Data Validation and Serialization
Both dataclasses and Pydantic models provide: ✅ Data validation: Type checking and coercion ✅ Data serialization: Converting to JSON-compatible formats ✅ Documentation: Automatic OpenAPI schema generation ✅ Editor support: Type hints and autocompleteCombining Dataclasses with Type Annotations
You can mix dataclasses with standard type annotations to create flexible data structures:Learn More
For more advanced usage and options:Dataclass support has been available since FastAPI version 0.67.0.