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.
pip install dataclasses-jsonschemaVerified import paths — ran on the pinned version, not inferred.
Define a dataclass that inherits from `JsonSchemaMixin`. Then, call the static method `.json_schema()` on the dataclass to retrieve the generated JSON schema. This example demonstrates basic field types and metadata usage.
Add `from __future__ import annotations` or use `typing.List[str]` for older Python versions.
Ensure `from __future__ import annotations` is present, or stick to `typing.List`/`typing.Union` for compatibility.
Understand its scope: schema generation. For validation, use a dedicated library like `jsonschema` or `Pydantic`.
Upgrade to version 2.15.3 or newer for robust handling of complex `Union` and `Optional` types.
Upgrade to version 2.15.0 or newer to use discriminators for OpenAPI 3.0 polymorphism.
Add `from __future__ import annotations` at the top of your file, or use `typing.List[str]` and `typing.Dict[str, int]` instead.
Ensure your dataclass definition includes `(JsonSchemaMixin)`: `@dataclass class MyDataclass(JsonSchemaMixin):`
Upgrade `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).