Pydantic Generator - PyCharter
Description: Data Contract Management, ETL Pipelines, and Quality Assurance for Python

Skip to content

# Pydantic Generator

Generate Pydantic models from JSON Schema.

## Overview

    from pycharter import from_dict, from_file, from_json

    User = from_dict(schema, "User")

## API Reference

### Input Functions

## `` from_dict

    from_dict(
        schema: dict[str, Any], model_name: str = "DynamicModel"
    ) -> Type[BaseModel]

Convert a JSON schema dictionary to a Pydantic model.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`schema` | `dict[str, Any]` | The JSON schema as a dictionary (must contain "version" field) | required
`model_name` | `str` | Name for the generated Pydantic model class | `'DynamicModel'`

Returns:

Type | Description
--- | ---
`Type[BaseModel]` | A Pydantic model class

Raises:

Type | Description
--- | ---
`ValueError` | If schema does not have a "version" field

Example

> > > schema = { ... "type": "object", ... "version": "1.0.0", ... "properties": { ... "name": {"type": "string", "description": "Person's name"}, ... "age": {"type": "integer", "description": "Person's age"} ... }, ... "required": ["name"] ... } Person = from_dict(schema, "Person") person = Person(name="Alice", age=30) person.name 'Alice' person.age 30

Source code in `src/pycharter/pydantic_generator/converter.py`

    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    def from_dict(
        schema: dict[str, Any], model_name: str = "DynamicModel"
    ) -> Type[BaseModel]:
        """
        Convert a JSON schema dictionary to a Pydantic model.

        Args:
            schema: The JSON schema as a dictionary (must contain "version" field)
            model_name: Name for the generated Pydantic model class

        Returns:
            A Pydantic model class

        Raises:
            ValueError: If schema does not have a "version" field

        Example:
            >>> schema = {
            ...     "type": "object",
            ...     "version": "1.0.0",
            ...     "properties": {
            ...         "name": {"type": "string", "description": "Person's name"},
            ...         "age": {"type": "integer", "description": "Person's age"}
            ...     },
            ...     "required": ["name"]
            ... }
            >>> Person = from_dict(schema, "Person")
            >>> person = Person(name="Alice", age=30)
            >>> person.name
            'Alice'
            >>> person.age
            30
        """
        validate_schema(schema)

        # Ensure schema has version
        if "version" not in schema:
            raise ValueError(
                "Schema must have a 'version' field. All schemas must be versioned. "
                "Please add 'version': '<version_string>' to your schema."
            )

        return schema_to_model(schema, model_name)

## `` from_file

    from_file(
        file_path: str | Path, model_name: str | None = None
    ) -> Type[BaseModel]

Load a JSON schema from a file and convert it to a Pydantic model.

Supports both JSON (.json) and YAML (.yaml, .yml) file formats.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`file_path` | `str | Path` | Path to the schema file (JSON or YAML, must contain "version" field) | required
`model_name` | `str | None` | Name for the generated Pydantic model class. If None, uses the file stem as the model name. | `None`

Returns:

Type | Description
--- | ---
`Type[BaseModel]` | A Pydantic model class

Raises:

Type | Description
--- | ---
`FileNotFoundError` | If file doesn't exist
`ValueError` | If schema does not have a "version" field or format is unsupported

Example

> > > ### JSON file

> > > Person = from_file("schema.json", "Person")

> > > ### YAML file

> > > Person = from_file("schema.yaml", "Person")

Source code in `src/pycharter/pydantic_generator/converter.py`

     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    def from_file(file_path: str | Path, model_name: str | None = None) -> Type[BaseModel]:
        """
        Load a JSON schema from a file and convert it to a Pydantic model.

        Supports both JSON (.json) and YAML (.yaml, .yml) file formats.

        Args:
            file_path: Path to the schema file (JSON or YAML, must contain "version" field)
            model_name: Name for the generated Pydantic model class.
                       If None, uses the file stem as the model name.

        Returns:
            A Pydantic model class

        Raises:
            FileNotFoundError: If file doesn't exist
            ValueError: If schema does not have a "version" field or format is unsupported

        Example:
            >>> # JSON file
            >>> Person = from_file("schema.json", "Person")
            >>> # YAML file
            >>> Person = from_file("schema.yaml", "Person")
        """
        path = Path(file_path)

        if not path.exists():
            raise FileNotFoundError(f"Schema file not found: {file_path}")

        if model_name is None:
            model_name = path.stem.capitalize()

        # Determine file format
        suffix = path.suffix.lower()

        if suffix in [".yaml", ".yml"]:
            with open(path, "r", encoding="utf-8") as f:
                schema = yaml.safe_load(f)
        elif suffix == ".json":
            with open(path, "r", encoding="utf-8") as f:
                schema = json.load(f)
        else:
            raise ValueError(
                f"Unsupported file format: {suffix}. Supported formats: .json, .yaml, .yml"
            )

        return from_dict(schema, model_name)

## `` from_json

    from_json(
        json_string: str, model_name: str = "DynamicModel"
    ) -> Type[BaseModel]

Convert a JSON schema string to a Pydantic model.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`json_string` | `str` | The JSON schema as a string (must contain "version" field) | required
`model_name` | `str` | Name for the generated Pydantic model class | `'DynamicModel'`

Returns:

Type | Description
--- | ---
`Type[BaseModel]` | A Pydantic model class

Raises:

Type | Description
--- | ---
`ValueError` | If schema does not have a "version" field

Example

> > > schema_json = ''' ... { ... "type": "object", ... "version": "1.0.0", ... "properties": { ... "name": {"type": "string"} ... } ... } ... ''' Person = from_json(schema_json, "Person")

Source code in `src/pycharter/pydantic_generator/converter.py`

    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    def from_json(json_string: str, model_name: str = "DynamicModel") -> Type[BaseModel]:
        """
        Convert a JSON schema string to a Pydantic model.

        Args:
            json_string: The JSON schema as a string (must contain "version" field)
            model_name: Name for the generated Pydantic model class

        Returns:
            A Pydantic model class

        Raises:
            ValueError: If schema does not have a "version" field

        Example:
            >>> schema_json = '''
            ... {
            ...     "type": "object",
            ...     "version": "1.0.0",
            ...     "properties": {
            ...         "name": {"type": "string"}
            ...     }
            ... }
            ... '''
            >>> Person = from_json(schema_json, "Person")
        """
        schema = json.loads(json_string)
        return from_dict(schema, model_name)

## `` from_url

    from_url(
        url: str, model_name: str = "DynamicModel"
    ) -> Type[BaseModel]

Load a JSON schema from a URL and convert it to a Pydantic model.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`url` | `str` | URL to the JSON schema (must contain "version" field) | required
`model_name` | `str` | Name for the generated Pydantic model class | `'DynamicModel'`

Returns:

Type | Description
--- | ---
`Type[BaseModel]` | A Pydantic model class

Raises:

Type | Description
--- | ---
`ValueError` | If schema does not have a "version" field

Example

> > > ### Load schema from a URL (must have version field)

> > > Person = from_url("https://example.com/schema.json", "Person")

Source code in `src/pycharter/pydantic_generator/converter.py`

    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    def from_url(url: str, model_name: str = "DynamicModel") -> Type[BaseModel]:
        """
        Load a JSON schema from a URL and convert it to a Pydantic model.

        Args:
            url: URL to the JSON schema (must contain "version" field)
            model_name: Name for the generated Pydantic model class

        Returns:
            A Pydantic model class

        Raises:
            ValueError: If schema does not have a "version" field

        Example:
            >>> # Load schema from a URL (must have version field)
            >>> Person = from_url("https://example.com/schema.json", "Person")
        """
        try:
            import urllib.request

            with urllib.request.urlopen(url) as response:
                schema = json.loads(response.read().decode())

            return from_dict(schema, model_name)
        except ImportError:
            raise ImportError(
                "urllib is required for from_url. It should be available in Python standard library."
            )
        except Exception as e:
            raise ValueError(f"Failed to load schema from URL: {e}")

## Examples

    from pycharter import from_dict, from_file, from_json

    # From dictionary
    schema = {
        "type": "object",
        "version": "1.0.0",
        "properties": {
            "name": {"type": "string"},
            "age": {"type": "integer"}
        }
    }
    User = from_dict(schema, "User")

    # From file
    Product = from_file("schemas/product.json", "Product")

    # From JSON string
    json_str = '{"type": "object", "properties": {...}}'
    Model = from_json(json_str, "Model")

    # Use the model
    user = User(name="Alice", age=30)
    print(user.model_dump())

## See Also

- JSON Schema Converter
- Validator