marshmallow-jsonschema: JSON Schema Generation from Marshmallow Schemas
marshmallow-jsonschema translates marshmallow schemas into JSON Schema Draft v7 compliant jsonschema. It enables developers to generate JSON Schemas directly from their existing Marshmallow schemas, which is particularly useful for frontend form generation, API documentation, or validation in other systems. The current version is 0.13.0, released in October 2021, suggesting a maintenance rather than a rapid release cadence.
Warnings
- breaking `marshmallow-jsonschema` is not compatible with `marshmallow.fields.Enum` introduced in Marshmallow v3.18.0. Using this field type will result in an `UnsupportedValueError`.
- deprecated When used with newer Marshmallow versions (e.g., v4.x), `marshmallow-jsonschema` may produce `RemovedInMarshmallow4Warning` warnings related to deprecated field attributes like `default` (use `dump_default`) and passing field `metadata` as keyword arguments (use explicit `metadata=` argument).
- gotcha `marshmallow-jsonschema` only supports converting Marshmallow schemas *to* JSON Schema. There is no built-in functionality to generate a Marshmallow schema *from* an existing JSON Schema.
Install
-
pip install marshmallow-jsonschema
Imports
- JSONSchema
from marshmallow_jsonschema import JSONSchema
Quickstart
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema
class UserSchema(Schema):
username = fields.String(required=True, metadata={'description': 'The user\'s unique identifier'})
age = fields.Integer(required=False, allow_none=True, metadata={'minimum': 0})
email = fields.Email(required=True)
# Instantiate the JSONSchema converter
json_schema_converter = JSONSchema()
# Convert your Marshmallow schema to a JSON Schema dictionary
user_json_schema = json_schema_converter.dump(UserSchema())
import json
print(json.dumps(user_json_schema, indent=2))