Yes, Pydantic v2 offers a way to construct a Pydantic model from a JSON schema at runtime using pydantic.TypeAdapter. This is a powerful feature for dynamic model creation.
Here's how it works:
from typing import Dict, Any
from pydantic import BaseModel, TypeAdapter
# Example JSON schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string", "default": "Unknown"}
},
"required": ["name", "age"]
}
# Create a TypeAdapter from the schema
adapter = TypeAdapter(BaseModel) # Use BaseModel as the base
# Validate and convert the JSON schema to a Pydantic model
try:
validated_data = adapter.validate_json(schema)
model = adapter.from_json(schema) # Alternative to validate_json + BaseModel(**validated_data)
print(model)
except Exception as e:
print(f"Error creating model from schema: {e}")
# Example with data conforming to the schema
data = {"name": "Alice", "age": 30}
try:
model_from_data = adapter.from_json(data)
print(model_from_data)
except Exception as e:
print(f"Error creating model from data: {e}")
Key points:
-
TypeAdapter(BaseModel): You create a TypeAdapter instance, specifying the base Pydantic model class (BaseModel in this case). This adapter will be used to validate and convert data according to the schema. You can use a more specific BaseModel subclass if you have common fields you want to include.
-
validate_json(schema): This method validates the JSON schema itself against the expected structure of a Pydantic model. It doesn't create an instance of the model; it just checks if the schema is valid. It returns a dictionary representing the validated data.
-
from_json(schema): This method is the most direct way to create a Pydantic model instance from a JSON schema or a dictionary. It combines validation and instantiation in one step. It's generally preferred over validate_json followed by BaseModel(**validated_data).
-
Error Handling: It's crucial to wrap the validate_json and from_json calls in try...except blocks to handle potential validation errors. The Exception type will catch most errors related to schema validation or data conversion.
-
Schema Requirements: The JSON schema must be compatible with Pydantic's schema format. Pydantic's documentation provides details on the supported schema properties and types.
-
Dynamic Model Creation: The real power of this approach is that you can dynamically generate the JSON schema at runtime (e.g., from a database, API response, or user input) and then use TypeAdapter to create a Pydantic model based on that schema.
Important Considerations:
- Base Model: The
BaseModel you use with TypeAdapter acts as a foundation. If the schema defines fields that are not present in the base model, they will be added dynamically. If the schema defines fields that conflict with the base model, the schema's definition will take precedence.
- Schema Complexity: For very complex schemas, you might need to create a custom
BaseModel with appropriate fields and validation logic to ensure that the generated model behaves as expected.
- Performance: Creating models from schemas at runtime can be less performant than using pre-defined models. If you need to create many models from the same schema, consider caching the
TypeAdapter instance.
This approach provides a flexible and powerful way to work with dynamic schemas in Pydantic v2. It's particularly useful when you need to integrate with systems that provide schemas in JSON format or when you need to create models based on user-defined schemas.