Skip to main content
https://github.com/s-knibbs/dataclasses-jsonschema/workflows/Tox%20tests/badge.svg?branch=master https://badge.fury.io/py/dataclasses-jsonschema.svg Language grade: Python

Please Note: This project is in maintenance mode. I’m currently only making urgent bugfixes.

A library to generate JSON Schema from python 3.7 dataclasses. Python 3.6 is supported through the dataclasses backport. Aims to be a more lightweight alternative to similar projects such as marshmallow & pydantic.

Feature Overview

  • Support for draft-04, draft-06, Swagger 2.0 & OpenAPI 3 schema types

  • Serialisation and deserialisation

  • Data validation against the generated schema

  • APISpec support. Example below:

Installation

~$ pip install dataclasses-jsonschema

For improved validation performance using fastjsonschema, install with:

~$ pip install dataclasses-jsonschema[fast-validation]

For improved uuid performance using fastuuid, install with:

~$ pip install dataclasses-jsonschema[fast-uuid]

For improved date and datetime parsing performance using ciso8601, install with:

~$ pip install dataclasses-jsonschema[fast-dateparsing]

Beware ciso8601 doesn’t support the entirety of the ISO 8601 spec, only a popular subset.

Examples

from dataclasses import dataclass

from dataclasses_jsonschema import JsonSchemaMixin


@dataclass
class Point(JsonSchemaMixin):
    "A 2D point"
    x: float
    y: float

Schema Generation

>>> pprint(Point.json_schema())
{
    'description': 'A 2D point',
    'type': 'object',
    'properties': {
        'x': {'format': 'float', 'type': 'number'},
        'y': {'format': 'float', 'type': 'number'}
    },
    'required': ['x', 'y']
}

Data Serialisation

>>> Point(x=3.5, y=10.1).to_dict()
{'x': 3.5, 'y': 10.1}

Deserialisation

>>> Point.from_dict({'x': 3.14, 'y': 1.5})
Point(x=3.14, y=1.5)
>>> Point.from_dict({'x': 3.14, y: 'wrong'})
dataclasses_jsonschema.ValidationError: 'wrong' is not of type 'number'

Generating multiple schemas

from dataclasses_jsonschema import JsonSchemaMixin, SchemaType

@dataclass
class Address(JsonSchemaMixin):
    """Postal Address"""
    building: str
    street: str
    city: str

@dataclass
class Company(JsonSchemaMixin):
    """Company Details"""
    name: str
    address: Address

>>> pprint(JsonSchemaMixin.all_json_schemas(schema_type=SchemaType.SWAGGER_V3))
{'Address': {'description': 'Postal Address',
             'properties': {'building': {'type': 'string'},
                            'city': {'type': 'string'},
                            'street': {'type': 'string'}},
             'required': ['building', 'street', 'city'],
             'type': 'object'},
 'Company': {'description': 'Company Details',
             'properties': {'address': {'$ref': '#/components/schemas/Address'},
                            'name': {'type': 'string'}},
             'required': ['name', 'address'],
             'type': 'object'}}

Custom validation using NewType

from dataclasses_jsonschema import JsonSchemaMixin, FieldEncoder

PhoneNumber = NewType('PhoneNumber', str)

class PhoneNumberField(FieldEncoder):

    @property
    def json_schema(self):
        return {'type': 'string', 'pattern': r'^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$'}

JsonSchemaMixin.register_field_encoders({PhoneNumber: PhoneNumberField()})

@dataclass
class Person(JsonSchemaMixin):
    name: str
    phone_number: PhoneNumber

For more examples see the tests

APISpec Plugin

New in v2.5.0

OpenAPI & Swagger specs can be generated using the apispec plugin:

from typing import Optional, List
from dataclasses import dataclass

from apispec import APISpec
from apispec_webframeworks.flask import FlaskPlugin
from flask import Flask, jsonify
import pytest

from dataclasses_jsonschema.apispec import DataclassesPlugin
from dataclasses_jsonschema import JsonSchemaMixin


# Create an APISpec
spec = APISpec(
    title="Swagger Petstore",
    version="1.0.0",
    openapi_version="3.0.2",
    plugins=[FlaskPlugin(), DataclassesPlugin()],
)


@dataclass
class Category(JsonSchemaMixin):
    """Pet category"""
    name: str
    id: Optional[int]

@dataclass
class Pet(JsonSchemaMixin):
    """A pet"""
    categories: List[Category]
    name: str


app = Flask(__name__)


@app.route("/random")
def random_pet():
    """A cute furry animal endpoint.
    ---
    get:
      description: Get a random pet
      responses:
        200:
          content:
            application/json:
              schema: Pet
    """
    pet = get_random_pet()
    return jsonify(pet.to_dict())

# Dependant schemas (e.g. 'Category') are added automatically
spec.components.schema("Pet", schema=Pet)
with app.test_request_context():
    spec.path(view=random_pet)

TODO

Release files for dataclasses-jsonschema 2.16.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dataclasses-jsonschema 2.16.0
File Size Uploaded
dataclasses-jsonschema-2.16.0.tar.gz 29.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for dataclasses-jsonschema 2.16.0
File Interpreter ABI Platform
dataclasses_jsonschema-2.16.0-py3-none-any.whl Python 3 none any Details

Total release size: 48.5 kB

Release files / dataclasses-jsonschema-2.16.0.tar.gz

Download URL dataclasses-jsonschema-2.16.0.tar.gz
Size 29.6 kB
Tags Source
SHA-256 checksum
How to use checksums
effb0c73db30a537a962da75c4f35b94a5b1b7c1b17806b1ef74aed8e0aa2768
BLAKE2b-256 checksum
How to use checksums
423285aa01902972b8f6bf933b69f3887e5840ec3afa6cbbeafb7bfca9276b51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.6.1 requests/2.22.0 setuptools/65.3.0 requests-toolbelt/0.9.1 tqdm/4.57.0 CPython/3.8.10

Release files / dataclasses_jsonschema-2.16.0-py3-none-any.whl

Download URL dataclasses_jsonschema-2.16.0-py3-none-any.whl
Size 18.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d203d6a16c990f7d09eae58c97ffaaea1e45ecb7a033d312e61e4c7836a741bf
BLAKE2b-256 checksum
How to use checksums
a2fcf8e6a8d753810e9b3b1799f9ac2e4bb33b0659e315236fba8da15317af81
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.6.1 requests/2.22.0 setuptools/65.3.0 requests-toolbelt/0.9.1 tqdm/4.57.0 CPython/3.8.10

Release history Release notifications | RSS feed

This release

2.16.0 This release

2 release files

2.15.2

1 release file

2.15.0

1 release file

2.14.0

1 release file

2.13.0

1 release file

2.12.1

1 release file

2.12.0

1 release file

2.11.1

1 release file

2.11.0

1 release file

2.10.1

1 release file

2.10.0

1 release file

2.9.0

1 release file

2.8.0

1 release file

2.7.3

1 release file

2.7.2

1 release file

2.6.2

1 release file

2.6.1

1 release file

2.6.0

1 release file

2.5.0

1 release file

2.4.0

1 release file

2.3.0

1 release file

2.2.0

1 release file

2.1.2

1 release file

2.1.1

1 release file

2.1.0

1 release file

2.0.0

1 release file

1.5.2

1 release file

1.5.1

1 release file

1.5.0

1 release file

1.4.3

1 release file

1.4.2

1 release file

1.4.1

1 release file

1.4.0

1 release file

1.3.0

1 release file

1.2.1

1 release file

1.2.0

1 release file

1.1.1

1 release file

1.1.0

1 release file

1.0.2

1 release file

1.0.1

1 release file

1.0.0

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page