dataclasses-jsonschema
The `dataclasses-jsonschema` library (current version 2.16.0) provides a straightforward way to generate JSON schemas from Python dataclasses. It augments dataclasses with a `JsonSchemaMixin` to expose schema generation capabilities and includes utilities for type conversion. The library maintains an active release cadence, frequently addressing bug fixes, improving type handling, and adding support for newer Python features.
Common errors
-
TypeError: 'type' object is not subscriptable
cause Using PEP 585 type hints (e.g., `list[str]`, `dict[str, int]`) without `from __future__ import annotations` on Python 3.8 or earlier.fixAdd `from __future__ import annotations` at the top of your file, or use `typing.List[str]` and `typing.Dict[str, int]` instead. -
AttributeError: type object 'MyDataclass' has no attribute 'json_schema'
cause The dataclass was not correctly inherited from `dataclasses_jsonschema.JsonSchemaMixin`.fixEnsure your dataclass definition includes `(JsonSchemaMixin)`: `@dataclass class MyDataclass(JsonSchemaMixin):` -
jsonschema.exceptions.ValidationError: 'None' is not of type 'string'
cause Schema generated for an `Optional[str]` field (or similar nullable type) might not correctly mark it as nullable, especially on older `dataclasses-jsonschema` versions or with complex `Union` types.fixUpgrade `dataclasses-jsonschema` to the latest version (2.15.3+) to improve `Union` and `Optional` handling. Ensure your dataclass field is correctly typed as `str | None` (Python 3.10+) or `Optional[str]` (Python < 3.10).
Warnings
- gotcha When using built-in generic types (e.g., `list[str]`, `dict[str, int]`) in Python versions older than 3.9, you must include `from __future__ import annotations` at the top of your module.
- breaking Support for PEP 585 (built-in generics like `list[str]`) and PEP 604 (union operator `|`) was introduced in version 2.14.0. If you upgrade to 2.14.0+ and start using these new syntaxes without `from __future__ import annotations` on Python < 3.9, your code might break.
- gotcha `dataclasses-jsonschema` is specifically designed for JSON schema generation from dataclasses. It does not provide runtime data validation, parsing, or serialization/deserialization like libraries such as Pydantic do. Trying to use it as a full-fledged data validation library will lead to unexpected behavior.
- gotcha Prior to version 2.15.0, handling of complex `Union` types, especially with `Optional` (e.g., `Optional[Union[A, B]]`), could lead to incorrect or incomplete schema generation. This was further refined in 2.15.2 and 2.15.3.
- breaking Discriminator support, crucial for OpenAPI 3.0 polymorphic schemas, was added in version 2.15.0. Any attempts to use discriminator functionality with versions older than 2.15.0 will not work as expected.
Install
-
pip install dataclasses-jsonschema
Imports
- JsonSchemaMixin
from dataclasses_jsonschema import JsonSchemaMixin
- dataclass
from dataclasses import dataclass
Quickstart
from dataclasses import dataclass, field
from datetime import datetime
from dataclasses_jsonschema import JsonSchemaMixin
@dataclass
class Person(JsonSchemaMixin):
name: str
age: int = field(metadata=dict(description="Age in years"))
birth_date: datetime
# Example with an optional field
email: str | None = None # Use typing.Optional for Python < 3.10
# Generate the JSON schema
schema = Person.json_schema()
# Print the generated schema
import json
print(json.dumps(schema, indent=2))