Data Contract Specification (Python Library)

1.2.3 · active · verified Sun Apr 12

The `datacontract-specification` Python library provides a Pydantic model for the Data Contract Specification. It allows users to define, load, and validate data contracts in a machine-readable YAML format, enabling programmatic interaction with data contract definitions. It's actively developed and frequently updated, mirroring the Data Contract Specification versions. The library serves as the programmatic core for tools like the `Data Contract CLI`.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a data contract definition from a YAML file using `DataContractSpecification.from_file()` and then access its properties. It creates a temporary YAML file with a basic contract for demonstration purposes.

import os
from datacontract_specification.model import DataContractSpecification

# Create a dummy data contract YAML file for the example
dummy_contract_content = """
dataContractSpecification: 1.2.0
id: urn:datacontract:example:orders-latest
info:
  title: Example Orders Latest
  version: 1.0.0
  description: |
    Successful customer orders example.
  owner: Example Team
  status: active
models:
  orders:
    type: table
    fields:
      order_id:
        type: string
        required: true
        description: Unique identifier for the order.
      customer_id:
        type: string
        description: Identifier for the customer.
"""

file_path = "example_datacontract.yaml"
with open(file_path, "w") as f:
    f.write(dummy_contract_content)

try:
    # Load the data contract from the file
    data_contract = DataContractSpecification.from_file(file_path)

    print("Data Contract Loaded Successfully:")
    print(data_contract.to_yaml())

    # Access some properties
    print(f"\nContract Title: {data_contract.info.title}")
    print(f"Contract Version: {data_contract.info.version}")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Clean up the dummy file
    if os.path.exists(file_path):
        os.remove(file_path)

view raw JSON →