All Projects → s-knibbs → dataclasses-jsonschema

s-knibbs / dataclasses-jsonschema

Licence: MIT license
JSON schema generation from dataclasses

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to dataclasses-jsonschema

Orjson
Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy
Stars: ✭ 2,595 (+1689.66%)
Mutual labels:  serialization, deserialization, dataclasses
dataconf
Simple dataclasses configuration management for Python with hocon/json/yaml/properties/env-vars/dict support.
Stars: ✭ 40 (-72.41%)
Mutual labels:  serialization, deserialization, dataclasses
CodableWrapper
@codec("encoder", "decoder") var cool: Bool = true
Stars: ✭ 143 (-1.38%)
Mutual labels:  serialization, deserialization
sexp-grammar
Invertible parsing for S-expressions
Stars: ✭ 28 (-80.69%)
Mutual labels:  serialization, deserialization
cattrs
Complex custom class converters for attrs.
Stars: ✭ 565 (+289.66%)
Mutual labels:  serialization, deserialization
bytes
Work with bytes and implement network protocols
Stars: ✭ 77 (-46.9%)
Mutual labels:  serialization, deserialization
json struct
json_struct is a single header only C++ library for parsing JSON directly to C++ structs and vice versa
Stars: ✭ 279 (+92.41%)
Mutual labels:  serialization, deserialization
serde
🚝 (unmaintained) A framework for defining, serializing, deserializing, and validating data structures
Stars: ✭ 49 (-66.21%)
Mutual labels:  serialization, deserialization
avro-serde-php
Avro Serialisation/Deserialisation (SerDe) library for PHP 7.3+ & 8.0 with a Symfony Serializer integration
Stars: ✭ 43 (-70.34%)
Mutual labels:  serialization, deserialization
parco
🏇🏻 generalist, fast and tiny binary parser and compiler generator, powered by Go 1.18+ Generics
Stars: ✭ 57 (-60.69%)
Mutual labels:  serialization, deserialization
avrow
Avrow is a pure Rust implementation of the avro specification https://avro.apache.org/docs/current/spec.html with Serde support.
Stars: ✭ 27 (-81.38%)
Mutual labels:  serialization, deserialization
moko-network
Network components with codegeneration of rest api for mobile (android & ios) Kotlin Multiplatform development
Stars: ✭ 107 (-26.21%)
Mutual labels:  serialization, openapi
har-rs
A HTTP Archive format (HAR) serialization & deserialization library, written in Rust.
Stars: ✭ 25 (-82.76%)
Mutual labels:  serialization, deserialization
marshmallow-validators
Use 3rd-party validators (e.g. from WTForms and colander) with marshmallow
Stars: ✭ 24 (-83.45%)
Mutual labels:  serialization, deserialization
pavlova
A python deserialisation library built on top of dataclasses
Stars: ✭ 32 (-77.93%)
Mutual labels:  deserialization, dataclasses
sqlathanor
Serialization / De-serialization support for the SQLAlchemy Declarative ORM
Stars: ✭ 105 (-27.59%)
Mutual labels:  serialization, deserialization
arrest
Swagger REST framework for Node.js, with support for MongoDB and JSON-Schema
Stars: ✭ 17 (-88.28%)
Mutual labels:  openapi, jsonschema
nason
🗜 Ultra tiny serializer / encoder with plugin-support. Useful to build binary files containing images, strings, numbers and more!
Stars: ✭ 30 (-79.31%)
Mutual labels:  serialization, deserialization
Jsonapi Rails
Rails gem for fast jsonapi-compliant APIs.
Stars: ✭ 242 (+66.9%)
Mutual labels:  serialization, deserialization
jsonargparse
Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables
Stars: ✭ 168 (+15.86%)
Mutual labels:  type-hints, dataclasses

Dataclasses JSON Schema

https://github.com/s-knibbs/dataclasses-jsonschema/workflows/Tox%20tests/badge.svg?branch=master 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]

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].