Skip to main content

Import: Pydantic Model

Creates a data contract from Pydantic model classes, the counterpart to datacontract export pydantic-model.

The module is read statically with Python's ast, never imported, so a contract can be derived from a service's models without installing that service's dependencies or executing any of its code.

Module-level models become schema objects, except those used as the type of another model's field: those are inlined as nested objects. Field(...) constraints become logicalTypeOptions, and Literal types and Enum classes become an invalidValues quality rule listing the valid values.

Given this orders.py:

import datetime
from enum import Enum
from typing import Optional

from pydantic import BaseModel, Field


class Status(str, Enum):
PENDING = "pending"
SHIPPED = "shipped"
DELIVERED = "delivered"


class Orders(BaseModel):
"""One row per customer order."""

order_id: str = Field(max_length=32)
order_timestamp: datetime.datetime
customer_id: Optional[str] = None
order_total: int = Field(description="Order total in cents.", ge=0)
status: Status

Run:

datacontract import pydantic-model --source orders.py

to produce the data contract:

version: 1.0.0
kind: DataContract
apiVersion: v3.1.0
id: my-data-contract
name: My Data Contract
status: draft
schema:
- name: Orders
physicalType: object
description: One row per customer order.
logicalType: object
physicalName: Orders
properties:
- name: order_id
physicalType: str
logicalType: string
logicalTypeOptions:
maxLength: 32
required: true
- name: order_timestamp
physicalType: datetime
logicalType: timestamp
required: true
- name: customer_id
physicalType: str
logicalType: string
required: false
- name: order_total
physicalType: int
description: Order total in cents.
logicalType: integer
logicalTypeOptions:
minimum: 0
required: true
# …

All options: datacontract import pydantic-model.