Pydantic-Driven CLI
Relevant source files
The following files were used as context for generating this wiki page:
The Pydantic-Driven CLI feature in flext-cli enables developers to build type-safe command-line interfaces by leveraging Pydantic 2 models. This approach eliminates the need for manual parameter definitions (such as standard Click decorators) by auto-generating CLI parameters, validation logic, and help text directly from data models. It ensures consistency between API schemas and CLI inputs, providing built-in validation and IDE autocomplete support.
Sources: examples/ex_12_pydantic_driven_cli.py:1-25, examples/README.md:14-16
Core Architecture and Components
The system relies on a set of core models and utilities that bridge the gap between Pydantic's data validation and the CLI's execution environment. The architecture promotes the "Railway Pattern" for error handling, ensuring that data flows through a series of validation and transformation steps or short-circuits on failure.
Key Components
| Component | Description |
|---|---|
CliModelConverter | Handles the conversion of Pydantic models into CLI-compatible parameters. |
FlextCliCommonParams | Provides auto-generated common parameters used across different CLI commands. |
m.Cli.LoadedConfig | A Pydantic model used to wrap and validate loaded configuration content. |
p.Result | A container for fallible operations, supporting ok and fail states. |
Sources: examples/ex_12_pydantic_driven_cli.py:27-31, src/flext_cli/_models/_base_parts/flextclimodelsbase_part_01.py:65-75, examples/ex_11_complete_integration.py:33-35
Data Flow Diagram
The following diagram illustrates the "Railway Pattern" data flow when processing CLI arguments into a validated Pydantic model.
Data Models and Normalization
flext-cli provides specialized base classes and models to handle JSON data normalization and display within the terminal.
Base Models for CLI Data
DisplayData: A Pydantic model designed for key-value pairs intended for table displays. It uses aMappingProxyTypeto ensure data integrity and includes a plain serializer to convert the internal data to a standard dictionary.CliNormalizedJson: Uses Pydantic'sRootModelto provide positional construction and root-level serialization for JSON-compatible values.SuccessSummaryDetails: A root model for mapping success details (key-value strings) often used in final CLI reports.
Sources: src/flext_cli/_models/_base_parts/flextclimodelsbase_part_01.py:34-63, src/flext_cli/_models/_base_parts/flextclimodelsbase_part_01.py:102-105
Implementation Example: Database Config
The system allows defining complex models with constraints that the CLI enforces during input parsing.
def convert_and_validate_with_pydantic(
data: t.JsonMapping,
) -> p.Result[m.Examples.AdvancedDatabaseConfig]:
"""Convert raw data to validated Pydantic model."""
try:
return r[m.Examples.AdvancedDatabaseConfig].ok(
m.Examples.AdvancedDatabaseConfig.model_validate(data),
)
except c.ValidationError as error:
return r[m.Examples.AdvancedDatabaseConfig].fail(
f"Pydantic validation failed: {error}",
)
Sources: examples/ex_12_pydantic_driven_cli.py:141-154
Execution Logic and Integration
The integration of Pydantic models into the CLI workflow is typically managed through service classes or functional pipelines.
The Service Base (s) pattern
The project encourages using a service base class (s) to provide consistent access to typed settings and result contracts. This class typically implements an execute method that returns a p.Result.
Integrated Workflow Features
- Prompt Runtime State: The CLI can be configured to be interactive or non-interactive using
m.Cli.PromptRuntimeState. - File Round-trips: Validated models can be persisted and reloaded through public facade methods like
read_json_modelandwrite_json_file, which maintain type safety throughout the I/O operation. - Output Formatting: Results stored in
m.Cli.DisplayDataor standard mappings can be rendered as tables usingcli.show_table.
Sources: examples/ex_11_complete_integration.py:42-50, examples/ex_01_getting_started.py:80-92, examples/ex_11_complete_integration.py:102-106
Summary
Pydantic-Driven CLI transformation in flext-cli centers on using Pydantic 2 models as the single source of truth for both data structure and CLI parameterization. By utilizing the p.Result railway pattern and specialized CLI models like DisplayData and LoadedConfig, the system ensures that developer-built tools are robust, type-safe, and highly maintainable with minimal boilerplate code.