🧬 yaml2pydantic¢

PyPI version codecov Documentation Python Version License: MIT

A powerful, extensible schema compiler that turns YAML/JSON definitions into dynamic Pydantic models β€” with full support for:

  • βœ… Custom types

  • βœ… Field and model-level validators

  • βœ… Custom serializers (field- and model-level)

  • βœ… Default values

  • βœ… Nested models

  • βœ… Reusable shared components

  • βœ… Auto-importing of components

  • βœ… Built-in type system

πŸ“š View the full documentation

Built for teams that want to define models declaratively in YAML but leverage all the power of Pydantic v2.


✨ Key Features¢

Feature

Description

πŸ“„ YAML/JSON to Pydantic

Define your models in YAML or JSON, and compile them into Pydantic models.

🧱 Custom Types

Extend your schema with types like Money, MonthYear, etc.

πŸ§ͺ Validators

Use reusable or model-specific validators (check_positive, etc.)

🎨 Serializers

Serialize fields or models however you want (Money β†’ "R$ 10,00")

πŸ” Field Defaults

Fully supports defaults for primitive and complex types

βš™οΈ Dynamic ModelFactory

All logic for building Pydantic models is centralized and pluggable

πŸ“š Registry-based architecture

Types, validators, serializers all managed through shared registries

πŸ”„ Auto-importing

Components are automatically imported from components directory

πŸ—οΈ Built-in Types

Support for common types like Money, MonthYear, and all Pydantic primitives


πŸš€ Quick Start (For Users)ΒΆ

InstallationΒΆ

pip install yaml2pydantic

Basic UsageΒΆ

  1. Define your model in YAML:

# models/user.yaml
User:
  fields:
    name:
      type: str
      max_length: 10
    age:
      type: int
      ge: 0
    email:
      type: Optional[str]
      default: null
  1. Use it in your Python code:

from yaml2pydantic import ModelFactory

# Load and compile the model
factory = ModelFactory()
User = factory.create_model("User", "models/user.yaml")

# Use it like any Pydantic model
user = User(
    name="John Doe",
    age=30,
    email="john@example.com"
)

Advanced Usage ExampleΒΆ

Here’s a more comprehensive example showing the full power of yaml2pydantic:

# models/user.yaml
User:
  fields:
    name:
      type: str
      max_length: 10  # Built-in Pydantic field constraints
    age:
      type: int
      ge: 0          # Built-in Pydantic field constraints
      validators:
        - check_positive  # Custom validator
    email:
      type: Optional[str]
      default: null
    birthday:
      type: datetime
    address:
      type: Address
      default:
        street: "Unknown"
        city: "Unknown"
        zip: "00000"
    balance:
      type: Money
      default: 0
      serializers:
        - money_as_string  # Custom serializer
    start_date:
      type: MonthYear
      default: "03/2025"

Address:
  fields:
    street:
      type: str
    city:
      type: str
    zip:
      type: str
      pattern: "^[0-9]{5}(-[0-9]{4})?$"
from yaml2pydantic import ModelFactory

# Load and compile the model
factory = ModelFactory()
User = factory.create_model("User", "models/user.yaml")

# Use it like any Pydantic model
user = User(
    name="John Doe",
    age=30,
    email="john@example.com",
    birthday="1990-01-01",
    address={
        "street": "123 Main St",
        "city": "Anytown",
        "zip": "12345"
    },
    balance=1000,
    start_date="03/2025"
)

Advanced FeaturesΒΆ


πŸ› οΈ Development Guide (For Contributors)ΒΆ

Project SetupΒΆ

# Clone the repository
git clone https://github.com/banduk/yaml2pydantic.git
cd yaml2pydantic

# Set up the development environment
make setup

# Activate the virtual environment
source .venv/bin/activate

Project StructureΒΆ

yaml2pydantic/
β”œβ”€β”€ main.py                       # Entry point to load + test models
β”œβ”€β”€ models/                       # YAML/JSON model definitions
β”‚   └── user.yaml
β”œβ”€β”€ components/                   # Shared reusable logic
β”‚   β”œβ”€β”€ serializers/              # Custom serialization functions
β”‚   β”‚   └── money.py              # Money-specific serializers
β”‚   β”œβ”€β”€ types/                    # Custom types (Money, MonthYear)
β”‚   β”‚   β”œβ”€β”€ money.py              # Money type implementation
β”‚   β”‚   └── monthyear.py          # MonthYear type implementation
β”‚   └── validators/               # Custom validation logic
β”‚       β”œβ”€β”€ email.py              # Email-related validators
β”‚       └── numeric.py            # Numeric validators
└── core/                         # Core schema engine
    β”œβ”€β”€ factory.py                # ModelFactory that builds Pydantic models
    β”œβ”€β”€ loader.py                 # Loads YAML, JSON, or dict input
    β”œβ”€β”€ registry.py               # Shared registries for types, validators, serializers
    β”œβ”€β”€ types.py                  # TypeRegistry
    β”œβ”€β”€ validators.py             # ValidatorRegistry
    └── serializers.py            # SerializerRegistry

Development WorkflowΒΆ

  1. Create a new feature branch:

    git checkout -b feature/your-feature-name
    
  2. Make your changes and run tests:

    make test
    
  3. Run code quality checks:

    make lint
    make format
    python -m mypy .
    
  4. Update documentation:

    make docs
    
  5. Submit a pull request

TestingΒΆ

# Run all tests
make test

# Run tests with coverage
python -m pytest --cov=yaml2pydantic

DocumentationΒΆ

# Build the documentation
make docs

# View the documentation
make docs-serve

Code QualityΒΆ

# Run the linter
make lint

# Format the code
make format

# Type check
make type-check

# Security check
make security-check

Or just run

make all-checks

πŸ“„ LicenseΒΆ

This project is licensed under the MIT License - see the LICENSE file for details.


🀝 Contributing¢

We welcome contributions! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.


πŸ“š DocumentationΒΆ

For detailed documentation, visit our documentation site.