Dydantic¶
Dydantic is a Python library for dynamically generating Pydantic models from JSON Schema. It provides a convenient way to create Pydantic models on-the-fly from general user-defined schemas.
Install¶
Reference¶
def create_model_from_schema(json_schema: Dict[str, Any],*, **kwargs: Any) -> Type[BaseModel]:
¶
Create a Pydantic model from a JSON schema.
This function takes a JSON schema as input and dynamically creates a Pydantic model class based on the schema. It supports various JSON schema features such as nested objects, referenced definitions, custom configurations, custom base classes, custom validators, and more.
Parameters:
-
json_schema
(Dict[str, Any]
) –A dictionary representing the JSON schema.
-
root_schema
(Optional[Dict[str, Any]]
, default:None
) –The root schema that contains the current schema. If not provided, the current schema will be treated as the root schema.
-
__config__
(ConfigDict | None
, default:None
) –Pydantic configuration for the generated model.
-
__base__
(None
, default:None
) –Base class for the generated model. Defaults to
pydantic.BaseModel
. -
__module__
(str
, default:__name__
) –Module name for the generated model class. Defaults to current module.
-
__validators__
(dict[str, AnyClassMethod] | None
, default:None
) –A dictionary of custom validators for the generated model.
-
__cls_kwargs__
(dict[str, Any] | None
, default:None
) –Additional keyword arguments for the generated model class.
Returns:
-
Type[BaseModel]
–A dynamically created Pydantic model class based on the provided JSON schema.
Examples:
-
Simple schema with string and integer properties:
>>> json_schema = { ... "title": "Person", ... "type": "object", ... "properties": { ... "name": {"type": "string"}, ... "age": {"type": "integer"}, ... }, ... "required": ["name"], ... } >>> Person = create_model_from_schema(json_schema) >>> person = Person(name="John", age=30) >>> person Person(name='John', age=30)
-
Schema with a nested object:
>>> json_schema = { ... "title": "Employee", ... "type": "object", ... "properties": { ... "name": {"type": "string"}, ... "age": {"type": "integer"}, ... "address": { ... "type": "object", ... "properties": { ... "street": {"type": "string"}, ... "city": {"type": "string"}, ... }, ... }, ... }, ... "required": ["name", "address"], ... } >>> Employee = create_model_from_schema(json_schema) >>> employee = Employee( ... name="Alice", age=25, address={"street": "123 Main St", "city": "New York"} ... ) >>> employee Employee(name='Alice', age=25, address=Address(street='123 Main St', city='New York'))
-
Schema with a referenced definition:
>>> json_schema = { ... "title": "Student", ... "type": "object", ... "properties": { ... "name": {"type": "string"}, ... "grade": {"type": "integer"}, ... "school": {"$ref": "#/$defs/School"}, ... }, ... "required": ["name", "school"], ... "$defs": { ... "School": { ... "type": "object", ... "properties": { ... "name": {"type": "string"}, ... "address": {"type": "string"}, ... }, ... "required": ["name"], ... }, ... }, ... } >>> Student = create_model_from_schema(json_schema) >>> student = Student( ... name="Bob", grade=10, school={"name": "ABC School", "address": "456 Elm St"} ... ) >>> student Student(name='Bob', grade=10, school=School(name='ABC School', address='456 Elm St'))
-
Schema with a custom configuration:
>>> json_schema = { ... "title": "User", ... "type": "object", ... "properties": { ... "username": {"type": "string"}, ... "email": {"type": "string", "format": "email"}, ... }, ... "required": ["username", "email"], ... } >>> config = ConfigDict(extra="forbid") >>> User = create_model_from_schema(json_schema, __config__=config) >>> user = User(username="john_doe", email="john@example.com") >>> user User(username='john_doe', email='john@example.com')
-
Schema with a custom base class:
>>> class CustomBaseModel(BaseModel): ... class Config: ... frozen = True >>> json_schema = { ... "title": "Product", ... "type": "object", ... "properties": { ... "name": {"type": "string"}, ... "price": {"type": "number"}, ... }, ... "required": ["name", "price"], ... } >>> Product = create_model_from_schema(json_schema, __base__=CustomBaseModel) >>> product = Product(name="Phone", price=499.99) >>> product Product(name='Phone', price=499.99) >>> product.price = 599.99 # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... pydantic_core._pydantic_core.ValidationError: 1 validation error for Product price Instance is frozen [type=frozen_instance, input_value=599.99, input_type=float]
-
Schema with a custom validator:
>>> from pydantic import field_validator >>> def price_validator(value): ... if value <= 0: ... raise ValueError("Price must be positive") ... return value >>> json_schema = { ... "title": "Item", ... "type": "object", ... "properties": { ... "name": {"type": "string"}, ... "price": {"type": "number"}, ... }, ... "required": ["name", "price"], ... } >>> Item = create_model_from_schema( ... json_schema, ... __validators__={ ... "my_price_validator": field_validator("price")(price_validator) ... }, ... ) >>> item = Item(name="Pen", price=-10) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... pydantic_core._pydantic_core.ValidationError: 1 validation error for Item price ValueError: Price must be positive
-
Schema with a union type using
anyOf
:>>> json_schema = { ... "title": "SKU", ... "type": "object", ... "properties": { ... "value": { ... "title": "Value", ... "anyOf": [ ... {"type": "string"}, ... {"type": "integer"}, ... {"type": "boolean"}, ... ], ... }, ... }, ... } >>> Sku = create_model_from_schema(json_schema) >>> Sku(value="hello") SKU(value='hello') >>> Sku(value=42) SKU(value=42) >>> Sku(value=True) SKU(value=True)
-
Schema with a string format:
>>> json_schema = { ... "title": "User", ... "type": "object", ... "properties": { ... "username": {"type": "string"}, ... "email": {"type": "string", "format": "email"}, ... "password": {"type": "string", "format": "password"}, ... }, ... "required": ["username", "email", "password"], ... } >>> User = create_model_from_schema(json_schema) >>> user = User(username="john_doe", email="john@example.com", password="secret") >>> user User(username='john_doe', email='john@example.com', password=SecretStr('**********')) >>> user.password SecretStr('**********')
-
Schema with an array of items:
>>> json_schema = { ... "title": "Numbers", ... "type": "object", ... "properties": { ... "value": { ... "type": "array", ... "items": {"type": "integer"}, ... } ... }, ... } >>> Numbers = create_model_from_schema(json_schema) >>> numbers = Numbers(value=[1, 2, 3, 4, 5]) >>> numbers Numbers(value=[1, 2, 3, 4, 5])
-
Schema with a nested array of objects:
>>> json_schema = { ... "title": "Matrix", ... "type": "object", ... "properties": { ... "value": { ... "type": "array", ... "items": { ... "type": "array", ... "items": {"type": "integer"}, ... }, ... }, ... }, ... } >>> Matrix = create_model_from_schema(json_schema) >>> matrix = Matrix(value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> matrix Matrix(value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Source code in dydantic/_utils.py
83 84 85 86 87 88 89 90 91 92 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 140 141 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
|
Contributing¶
Contributions to dydantic are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the GitHub repository: https://github.com/hinthornw/dydantic
License¶
dydantic
is open-source software licensed under the MIT License.