ModelManager class¶
Here's the reference information for the ModelManager class, with all its
parameters, attributes and methods.
This is the main class you interact with in pyrmute.
You can import the ModelManager class directly from pyrmute:
pyrmute.ModelManager
¶
High-level interface for versioned model management and schema generation.
ModelManager provides a unified API for managing schema evolution across different versions of Pydantic models. It handles model registration, automatic migration between versions, customizable schema generation, and batch processing operations.
Example
Basic Usage:
from pyrmute import ModelManager, ModelData
manager = ModelManager()
# Register model versions
@manager.model("User", "1.0.0")
class UserV1(BaseModel):
name: str
@manager.model("User", "2.0.0")
class UserV2(BaseModel):
name: str
email: str
# Define migration between versions
@manager.migration("User", "1.0.0", "2.0.0")
def migrate(data: ModelData) -> ModelData:
return {**data, "email": "unknown@example.com"}
# Migrate legacy data
old_data = {"name": "Alice"}
user = manager.migrate(old_data, "User", "1.0.0", "2.0.0")
# Result: UserV2(name="Alice", email="unknown@example.com")
Custom Schema Generation:
from pydantic.json_schema import GenerateJsonSchema
class CustomSchemaGenerator(GenerateJsonSchema):
'''Add custom metadata to all schemas.'''
def generate(
self,
schema: Mapping[str, Any],
mode: JsonSchemaMode = "validation"
) -> JsonSchema:
json_schema = super().generate(schema, mode=mode)
json_schema["x-company"] = "Acme"
json_schema["$schema"] = self.schema_dialect
return json_schema
# Set at manager level (applies to all schemas)
manager = ModelManager(
default_schema_config=SchemaConfig(
schema_generator=CustomSchemaGenerator,
mode="validation",
by_alias=True
)
)
@manager.model("User", "1.0.0")
class User(BaseModel):
name: str = Field(title="Full Name")
email: str
# Get schema with default config
schema = manager.get_schema("User", "1.0.0")
# Will include x-company: "Acme"
Advanced Features:
# Batch migration with parallel processing
users = manager.migrate_batch(
legacy_users, "User", "1.0.0", "2.0.0",
parallel=True, max_workers=4
)
# Stream large datasets efficiently
for user in manager.migrate_batch_streaming(
large_dataset, "User", "1.0.0", "2.0.0"
):
save_to_database(user)
# Compare versions and export schemas
diff = manager.diff("User", "1.0.0", "2.0.0")
print(diff.to_markdown())
manager.dump_schemas("schemas/", separate_definitions=True)
# Test migrations with validation
results = manager.test_migration(
"User", "1.0.0", "2.0.0",
test_cases=[
(
{"name": "Alice"},
{"name": "Alice", "email": "unknown@example.com"}
)
]
)
results.assert_all_passed()
Schema Transformers:
manager = ModelManager()
@manager.model("Product", "1.0.0")
class Product(BaseModel):
name: str
price: float
# Add transformer for specific model
@manager.schema_transformer("Product", "1.0.0")
def add_examples(schema: JsonSchema) -> JsonSchema:
schema["examples"] = [{"name": "Widget", "price": 9.99}]
return schema
schema = manager.get_schema("Product", "1.0.0")
# Will include examples
Initialize the versioned model manager.
| PARAMETER | DESCRIPTION |
|---|---|
default_schema_config
|
Default configuration for schema generation applied to all schema operations unless overridden.
TYPE:
|
Source code in src/pyrmute/model_manager.py
model
¶
Register a versioned model.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Semantic version.
TYPE:
|
enable_ref
|
If True, this model can be referenced via $ref in separate schema files. If False, it will always be inlined.
TYPE:
|
backward_compatible
|
If True, this model does not need a migration function to migrate to the next version. If a migration function is defined it will use it.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[type[DecoratedBaseModel]], type[DecoratedBaseModel]]
|
Decorator function for model class. |
Example
Source code in src/pyrmute/model_manager.py
get
¶
Get a model by name and version.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Semantic version (returns latest if None).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
type[BaseModel]
|
Model class. |
Source code in src/pyrmute/model_manager.py
get_latest
¶
Get the latest version of a model by name.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
type[BaseModel]
|
Model class. |
get_nested_models
¶
Get all nested models used by a model.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Semantic version.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[NestedModelInfo]
|
List of NestedModelInfo. |
Source code in src/pyrmute/model_manager.py
list_models
¶
Get list of all registered models.
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
List of model names. |
list_versions
¶
Get all versions for a model.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[ModelVersion]
|
Sorted list of versions. |
migration
¶
Register a migration function.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[MigrationFunc], MigrationFunc]
|
Decorator function for migration function. |
Source code in src/pyrmute/model_manager.py
add_hook
¶
Register a migration hook for observability/logging.
| PARAMETER | DESCRIPTION |
|---|---|
hook
|
Migration hook instance to register.
TYPE:
|
Example
from pyrmute import MetricsHook, MigrationHook
import logging
# Use built-in metrics hook
metrics = MetricsHook()
manager.add_hook(metrics)
# Add custom logging hook
class LoggingHook(MigrationHook):
def before_migrate(
self,
name: str,
from_version: ModelVersion,
to_version: ModelVersion,
data: Mapping[str, Any],
) -> None:
logging.info(f"Starting migration: {name}")
return data
manager.add_hook(LoggingHook())
Source code in src/pyrmute/model_manager.py
remove_hook
¶
Remove a previously registered hook.
| PARAMETER | DESCRIPTION |
|---|---|
hook
|
Migration hook instance to remove.
TYPE:
|
clear_hooks
¶
has_migration_path
¶
Check if a migration path exists between two versions.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if a migration path exists, False otherwise. |
Example
Source code in src/pyrmute/model_manager.py
validate_data
¶
Check if data is valid for a specific model version.
Validates whether the provided data conforms to the schema of the specified model version without raising an exception.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data dictionary to validate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
version
|
Semantic version to validate against.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if data is valid for the model version, False otherwise. |
Example
Source code in src/pyrmute/model_manager.py
migrate
¶
Migrate data between versions.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data dictionary to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BaseModel
|
Migrated BaseModel. |
Source code in src/pyrmute/model_manager.py
migrate_as
¶
Migrate data between versions with type safety.
This is a type-safe variant of migrate() that returns a specific model type when you provide the target type explicitly.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data dictionary to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
target_type
|
The expected model class type.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DecoratedBaseModel
|
Migrated model instance of the specified type. |
Example
Source code in src/pyrmute/model_manager.py
migrate_data
¶
Migrate data between versions.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data dictionary to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ModelData
|
Raw migrated dictionary. |
Source code in src/pyrmute/model_manager.py
migrate_batch
¶
migrate_batch(
data_list,
name,
from_version,
to_version,
parallel=False,
max_workers=None,
use_processes=False,
)
Migrate multiple data items between versions.
| PARAMETER | DESCRIPTION |
|---|---|
data_list
|
Iterable of data dictionaries to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
parallel
|
If True, use parallel processing.
TYPE:
|
max_workers
|
Maximum number of workers for parallel processing.
TYPE:
|
use_processes
|
If True, use ProcessPoolExecutor instead of ThreadPoolExecutor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[BaseModel]
|
List of migrated BaseModel instances. |
Source code in src/pyrmute/model_manager.py
migrate_batch_as
¶
migrate_batch_as(
data_list,
name,
from_version,
to_version,
target_type,
parallel=False,
max_workers=None,
use_processes=False,
)
Migrate multiple data items between versions with type safety.
This is a type-safe variant of migrate_batch() that returns a specific model type when you provide the target type explicitly.
| PARAMETER | DESCRIPTION |
|---|---|
data_list
|
Iterable of data dictionaries to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
target_type
|
The expected model class type.
TYPE:
|
parallel
|
If True, use parallel processing.
TYPE:
|
max_workers
|
Maximum number of workers for parallel processing.
TYPE:
|
use_processes
|
If True, use ProcessPoolExecutor instead of ThreadPoolExecutor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[DecoratedBaseModel]
|
List of migrated model instances of the specified type. |
Example
Source code in src/pyrmute/model_manager.py
migrate_batch_data
¶
migrate_batch_data(
data_list,
name,
from_version,
to_version,
parallel=False,
max_workers=None,
use_processes=False,
)
Migrate multiple data items between versions, returning raw dictionaries.
| PARAMETER | DESCRIPTION |
|---|---|
data_list
|
Iterable of data dictionaries to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
parallel
|
If True, use parallel processing.
TYPE:
|
max_workers
|
Maximum number of workers for parallel processing.
TYPE:
|
use_processes
|
If True, use ProcessPoolExecutor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[ModelData]
|
List of raw migrated dictionaries. |
Source code in src/pyrmute/model_manager.py
migrate_batch_streaming
¶
Migrate data in chunks, yielding results as they complete.
| PARAMETER | DESCRIPTION |
|---|---|
data_list
|
Iterable of data dictionaries to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
chunk_size
|
Number of items to process in each chunk.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
Iterable[BaseModel]
|
Migrated BaseModel instances. |
Source code in src/pyrmute/model_manager.py
migrate_batch_streaming_as
¶
migrate_batch_streaming_as(
data_list,
name,
from_version,
to_version,
target_type,
chunk_size=100,
)
Migrate data in chunks with type safety, yielding results as they complete.
This is a type-safe variant of migrate_batch_streaming() that returns a specific model type when you provide the target type explicitly.
| PARAMETER | DESCRIPTION |
|---|---|
data_list
|
Iterable of data dictionaries to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
target_type
|
The expected model class type.
TYPE:
|
chunk_size
|
Number of items to process in each chunk.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
Iterable[DecoratedBaseModel]
|
Migrated model instances of the specified type. |
Example
Source code in src/pyrmute/model_manager.py
migrate_batch_data_streaming
¶
Migrate data in chunks, yielding raw dictionaries as they complete.
| PARAMETER | DESCRIPTION |
|---|---|
data_list
|
Iterable of data dictionaries to migrate.
TYPE:
|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
chunk_size
|
Number of items to process in each chunk.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
Iterable[ModelData]
|
Raw migrated dictionaries. |
Source code in src/pyrmute/model_manager.py
test_migration
¶
Test a migration with multiple test cases.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version to migrate from.
TYPE:
|
to_version
|
Target version to migrate to.
TYPE:
|
test_cases
|
List of test cases.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MigrationTestResults
|
MigrationTestResults containing individual results for each test case. |
Source code in src/pyrmute/model_manager.py
diff
¶
Get a detailed diff between two model versions.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
from_version
|
Source version.
TYPE:
|
to_version
|
Target version.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ModelDiff
|
ModelDiff with detailed change information. |
Source code in src/pyrmute/model_manager.py
set_default_schema_generator
¶
Set the default schema generator for all schemas.
This is a convenience method that updates the default schema configuration.
| PARAMETER | DESCRIPTION |
|---|---|
generator
|
Custom schema generator - either a callable or GenerateJsonSchema class.
TYPE:
|
Example
Class:
from pydantic.json_schema import GenerateJsonSchema
class MyGenerator(GenerateJsonSchema):
def generate(
self,
schema: Mapping[str, Any],
mode: JsonSchemaMode = "validation"
) -> JsonSchema:
json_schema = super().generate(schema, mode=mode)
json_schema["x-custom"] = True
json_schema["$schema"] = self.schema_dialect
return json_schema
manager = ModelManager()
manager.set_default_schema_generator(MyGenerator)
# All subsequent schema calls will use MyGenerator
schema = manager.get_schema("User", "1.0.0")
Callable:
Source code in src/pyrmute/model_manager.py
schema_transformer
¶
Decorator to register a schema transformer for a model version.
Transformers are simple functions that modify a schema after generation. They're useful for model-specific customizations that don't require deep integration with Pydantic's generation process.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Model version.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[SchemaTransformer], SchemaTransformer]
|
Decorator function. |
Example
@manager.schema_transformer("User", "1.0.0")
def add_auth_metadata(schema: JsonSchema) -> JsonSchema:
schema["x-requires-auth"] = True
schema["x-auth-level"] = 'admin'
return schema
@manager.schema_transformer("Product", "2.0.0")
def add_product_examples(schema: JsonSchema) -> JsonSchema:
schema["examples"] = [
{"name": "Widget", "price": 9.99},
{"name": "Gadget", "price": 19.99}
]
return schema
Source code in src/pyrmute/model_manager.py
get_schema_transformers
¶
Get all transformers for a model version.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Model version.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[SchemaTransformer]
|
List of transformer functions. |
Example
Source code in src/pyrmute/model_manager.py
clear_schema_transformers
¶
Clear schema transformers.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Optional model name. If None, clears all.
TYPE:
|
version
|
Optional version. If None, clears all versions of model.
TYPE:
|
Example
Source code in src/pyrmute/model_manager.py
get_schema
¶
Get JSON schema for a specific version.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Semantic version.
TYPE:
|
config
|
Optional schema configuration (overrides default).
TYPE:
|
**kwargs
|
Additional schema generation arguments (e.g., mode="serialization").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
JsonSchema
|
JSON schema dictionary. |
Example
Source code in src/pyrmute/model_manager.py
dump_schemas
¶
Export all schemas to JSON files.
| PARAMETER | DESCRIPTION |
|---|---|
output_dir
|
Directory path for output.
TYPE:
|
indent
|
JSON indentation level.
TYPE:
|
separate_definitions
|
If True, create separate schema files for nested models and use $ref to reference them.
TYPE:
|
ref_template
|
Template for $ref URLs when separate_definitions=True.
TYPE:
|
config
|
Optional schema configuration for all exported schemas.
TYPE:
|
Example
# Export with custom generator
config = SchemaConfig(
schema_generator=CustomGenerator,
mode="validation"
)
manager.dump_schemas("schemas/", config=config)
# Export validation and serialization schemas separately
manager.dump_schemas(
"schemas/validation/",
config=SchemaConfig(mode="validation")
)
manager.dump_schemas(
"schemas/serialization/",
config=SchemaConfig(mode="serialization")
)
Source code in src/pyrmute/model_manager.py
get_avro_schema
¶
Get Avro schema for a specific model version.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Semantic version.
TYPE:
|
namespace
|
Avro namespace. If None, uses "com.example".
TYPE:
|
include_docs
|
Whether to include field descriptions.
TYPE:
|
versioned_namespace
|
Include model version in namespace. Default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AvroRecordSchema
|
Avro schema typed dictionary. |
Example
# Get Avro schema for a model
schema = manager.get_avro_schema("User", "1.0.0", namespace="com.myapp")
# Use with fastavro
import fastavro
with open("users.avro", "wb") as out:
fastavro.writer(out, schema, records)
# Use with Kafka
from confluent_kafka import avro
producer = avro.AvroProducer({
"bootstrap.servers": "localhost:9092",
"schema.registry.url": "http://localhost:8081"
}, default_value_schema=avro.loads(json.dumps(schema)))
Source code in src/pyrmute/model_manager.py
dump_avro_schemas
¶
dump_avro_schemas(
output_dir,
namespace=None,
indent=2,
include_docs=True,
versioned_namespace=False,
)
Export all schemas as Apache Avro schemas.
Avro is commonly used in data engineering and event streaming, particularly with Apache Kafka, Hadoop, and data lakes.
| PARAMETER | DESCRIPTION |
|---|---|
output_dir
|
Directory path for output.
TYPE:
|
namespace
|
Avro namespace (e.g., "com.mycompany.events"). If None, uses "com.example".
TYPE:
|
indent
|
JSON indentation level.
TYPE:
|
include_docs
|
Whether to include field descriptions in schemas.
TYPE:
|
versioned_namespace
|
Include model versions in namespaces. Default False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, AvroRecordSchema]]
|
Dictionary mapping model names to versions to Avro schemas. |
Example
# Export all models as Avro schemas
manager.dump_avro_schemas(
"schemas/avro/",
namespace="com.mycompany.events",
include_docs=True
)
# Creates files like:
# schemas/avro/User_v1_0_0.avsc
# schemas/avro/User_v2_0_0.avsc
# schemas/avro/Order_v1_0_0.avsc
# Use with Kafka Schema Registry
from confluent_kafka.schema_registry import SchemaRegistryClient
client = SchemaRegistryClient({"url": "http://localhost:8081"})
with open("schemas/avro/User_v1_0_0.avsc") as f:
schema_str = f.read()
client.register_schema("user-value", schema_str)
Source code in src/pyrmute/model_manager.py
get_proto_schema
¶
Get Protocol Buffer schema for a specific model version.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Semantic version.
TYPE:
|
package
|
Protobuf package name (e.g., "com.mycompany.users"). This is a namespace that remains consistent across versions. Defaults to "com.example".
TYPE:
|
include_docs
|
Whether to include documentation as comments.
TYPE:
|
use_proto3
|
Use proto3 syntax (True) or proto2 (False). Defaults to True (proto3 is recommended for new projects).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Protocol Buffer file as a string. |
Example
Source code in src/pyrmute/model_manager.py
dump_proto_schemas
¶
Export all schemas as Protocol Buffer schemas.
Protocol Buffers are commonly used for gRPC, microservices communication, and efficient binary serialization.
| PARAMETER | DESCRIPTION |
|---|---|
output_dir
|
Directory path for output.
TYPE:
|
package
|
Protobuf package name (e.g., "com.mycompany.events"). This namespace remains consistent across all versions. Defaults to "com.example".
TYPE:
|
include_docs
|
Whether to include documentation as comments.
TYPE:
|
use_proto3
|
Use proto3 syntax (True) or proto2 (False). Defaults to True (proto3 is recommended for new projects).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, str]]
|
Dictionary mapping model names to versions to Protocol Buffer schemas. |
Example
# Export all models as proto3 schemas
manager.dump_proto_schemas(
"schemas/protos/",
package="com.mycompany.events",
include_docs=True,
use_proto3=True,
)
# Creates files like:
# schemas/protos/User_v1_0_0.proto
# schemas/protos/User_v2_0_0.proto
# schemas/protos/Order_v1_0_0.proto
# Compile with protoc:
# protoc --go_out=. schemas/protos/*.proto
Source code in src/pyrmute/model_manager.py
get_typescript_schema
¶
Get TypeScript schema for a specific model version.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the model.
TYPE:
|
version
|
Semantic version.
TYPE:
|
style
|
Output style - 'interface', 'type', or 'zod'.
TYPE:
|
config
|
Optional configuration for schema generation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
TypeScript schema code as a string. |
Example
# Get TypeScript interface for a model
schema = manager.get_typescript_schema("User", "1.0.0", style="interface")
print(schema)
# export interface UserV1_0_0 {
# name: string;
# email: string;
# age?: number;
# }
# Get Zod schema with validation
zod_schema = manager.get_typescript_schema("User", "2.0.0", style="zod")
print(zod_schema)
# import { z } from 'zod';
#
# export const UserV2_0_0Schema = z.object({
# name: z.string(),
# email: z.string().email(),
# age: z.number().int().positive().optional(),
# });
#
# export type UserV2_0_0 = z.infer<typeof UserV2_0_0Schema>;
# Customize output with config
from pyrmute.typescript_types import TypeScriptConfig
config = TypeScriptConfig(
date_format="timestamp",
enum_style="enum",
strict_null_checks=True,
)
schema = manager.get_typescript_schema(
"Event", "1.0.0", style="interface", config=config
)
# Use in frontend
# Save to file and import in TypeScript:
# import { UserV1_0_0 } from './types/user_v1_0_0';
#
# const user: UserV1_0_0 = {
# name: "Alice",
# email: "alice@example.com"
# };
# Use with Zod for runtime validation
# import { UserV2_0_0Schema } from './schemas/user_v2_0_0';
#
# const result = UserV2_0_0Schema.safeParse(data);
# if (result.success) {
# console.log(result.data);
# } else {
# console.error(result.error);
# }
Source code in src/pyrmute/model_manager.py
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 | |
dump_typescript_schemas
¶
dump_typescript_schemas(
output_dir,
style="interface",
config=None,
organization="flat",
include_barrel_exports=True,
)
Export all schemas as TypeScript schemas.
TypeScript schemas enable type-safe frontend development and can include runtime validation with Zod. Ideal for full-stack applications where backend Pydantic models need to be synchronized with frontend TypeScript code.
| PARAMETER | DESCRIPTION |
|---|---|
output_dir
|
Directory path for output.
TYPE:
|
style
|
Output style - 'interface' (default), 'type', or 'zod'.
TYPE:
|
config
|
Optional configuration for schema generation.
TYPE:
|
organization
|
Directory structure for output files: - 'flat': All files in output directory (Model.v1.0.0.ts) - 'major_version': Organize by major version (v1/Model.v1.0.0.ts) - 'model': Organize by model name (Model/1.0.0.ts)
TYPE:
|
include_barrel_exports
|
Whether to generate index.ts files for easier imports.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, str]]
|
Dictionary mapping model names to versions to TypeScript schema code. |
Example
# Export all models as TypeScript interfaces (flat structure)
manager.dump_typescript_schemas(
"frontend/src/types/",
style="interface"
)
# Creates files like:
# frontend/src/types/User.v1.0.0.ts
# frontend/src/types/User.v2.0.0.ts
# frontend/src/types/Order.v1.0.0.ts
# Export organized by major version (recommended)
manager.dump_typescript_schemas(
"frontend/src/types/",
style="interface",
organization="major_version"
)
# Creates:
# frontend/src/types/v1/User.v1.0.0.ts
# frontend/src/types/v1/index.ts
# frontend/src/types/v2/User.v2.0.0.ts
# frontend/src/types/v2/index.ts
# frontend/src/types/index.ts (re-exports latest)
# Export organized by model
manager.dump_typescript_schemas(
"frontend/src/types/",
organization="model"
)
# Creates:
# frontend/src/types/User/1.0.0.ts
# frontend/src/types/User/2.0.0.ts
# frontend/src/types/User/index.ts (re-exports latest)
# frontend/src/types/Order/1.0.0.ts
# frontend/src/types/Order/index.ts
# frontend/src/types/index.ts
# Export as Zod schemas with validation
manager.dump_typescript_schemas(
"frontend/src/schemas/",
style="zod",
organization="major_version"
)
# Export with custom configuration
from pyrmute.typescript_types import TypeScriptConfig
config = TypeScriptConfig(
strict_null_checks=True,
date_format="iso", # or "timestamp"
enum_style="union", # or "enum"
)
manager.dump_typescript_schemas(
"frontend/src/types/",
style="interface",
config=config,
organization="major_version"
)
# Use in React application with barrel exports
# import { User } from '@/types/v1'; // Gets latest v1
# import { Order } from '@/types'; // Gets latest version
#
# interface UserCardProps {
# user: User;
# }
#
# export function UserCard({ user }: UserCardProps) {
# return <div>{user.name}</div>;
# }
# Use Zod for API response validation
# import { UserSchema } from '@/schemas/v1';
#
# async function fetchUser(id: string) {
# const response = await fetch(`/api/users/${id}`);
# const data = await response.json();
# return UserSchema.parse(data); // Validates at runtime
# }
# Use with tRPC for end-to-end type safety
# import { UserSchema } from '@/schemas/v1';
#
# export const userRouter = router({
# getUser: publicProcedure
# .input(z.object({ id: z.string() }))
# .output(UserSchema)
# .query(async ({ input }) => {
# return await db.user.findUnique({ where: { id: input.id } });
# }),
# });
# Integrate with build pipeline
# Add to package.json scripts:
# {
# "scripts": {
# "generate-types": "python -m pyrmute export -f typescript -o src/types",
# "prebuild": "npm run generate-types"
# }
# }
Source code in src/pyrmute/model_manager.py
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 | |