GithubHelp home page GithubHelp logo

isabella232 / dataclasses-jsonschema Goto Github PK

View Code? Open in Web Editor NEW

This project forked from dbt-labs/dataclasses-jsonschema

0.0 0.0 0.0 83 KB

JSON schema generation from dataclasses

License: MIT License

Python 100.00%

dataclasses-jsonschema's Introduction

Dataclasses JSON Schema

https://travis-ci.org/s-knibbs/dataclasses-jsonschema.svg?branch=master Language grade: Python

A lightweight library to generate JSON Schema from python 3.7 dataclasses. Python 3.6 is supported through the dataclasses backport. Also supports the following features:

  • Generate schemas that can be embedded into Swagger / OpenAPI 2.0 and 3.0 specs
  • Serialisation and deserialisation
  • Data validation against the generated schema

Installation

~$ pip install dataclasses-jsonschema

For improved validation performance using PyValico, install with:

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

Examples

from dataclasses import dataclass

from dataclasses_jsonschema import JsonSchemaMixin


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

Generate the schema:

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

Serialise data:

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

Deserialise data:

>>> 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'

Generate a schema for embedding into an API spec:

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 rules can be added 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

TODO

KNOWN ISSUES

The following will currently fail when installed alongside pyvalico==0.0.2

@dataclass
class Baz(JsonSchemaMixin):
    """Type with nested default value"""
    a: Point = field(default=Point(0.0, 0.0))

Baz.from_dict({})

The workaround is to pin pyvalico to v0.0.1

dataclasses-jsonschema's People

Contributors

beckjake avatar cmcarthur avatar s-knibbs avatar snorfalorpagus avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.