Skip to main content

Convert YAML schemas to Pydantic models

Project description

๐Ÿงฌ yaml2pydantic

PyPI version Python Version License: MIT CI Status Documentation Status Security Scan

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

yaml2pydantic-0.0.3.tar.gz (11.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

yaml2pydantic-0.0.3-py3-none-any.whl (10.0 kB view details)

Uploaded Python 3

File details

Details for the file yaml2pydantic-0.0.3.tar.gz.

File metadata

  • Download URL: yaml2pydantic-0.0.3.tar.gz
  • Upload date:
  • Size: 11.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for yaml2pydantic-0.0.3.tar.gz
Algorithm Hash digest
SHA256 3d5363097de33da72fd8200bb1da64fb35e8114e43d82114508e19bfaef85a27
MD5 41abd9fa7073c96b5d0ce9663a300eaa
BLAKE2b-256 7cda30ee2541df36d5d37e559d241fba96fd98039871bd1130929fcabaaf2f09

See more details on using hashes here.

File details

Details for the file yaml2pydantic-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: yaml2pydantic-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 10.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for yaml2pydantic-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 f811b372bb00fcd8a7857f54f08b67eb85bda38f1d0b1e662d0ce2717de1aeef
MD5 7795755676329231249693625be7c8ad
BLAKE2b-256 d46ed4e4d4d4fa78b6df95a886ae0caf113609b8c95e1e6fd5f31e1666756535

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page