Package: dataclasses-jsonschema-rereleased
A library to generate JSON Schema from python 3.7 dataclasses. Python 3.6 is supported through thedataclasses backport. Aims to be a more lightweight alternative to similar projects such asmarshmallow&pydantic.Feature OverviewSupport for draft-04, draft-06, Swagger 2.0 & OpenAPI 3 schema typesSerialisation and deserialisationData validation against the generated schemaAPISpecsupport. Examplebelow:Installation~$pipinstalldataclasses-jsonschemaFor improved validation performance usingfastjsonschema, install with:~$pipinstalldataclasses-jsonschema[fast-validation]Examplesfromdataclassesimportdataclassfromdataclasses_jsonschemaimportJsonSchemaMixin@dataclassclassPoint(JsonSchemaMixin):"A 2D point"x:floaty:floatSchema 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'isnotoftype'number'Generating multiple schemasfromdataclasses_jsonschemaimportJsonSchemaMixin,SchemaType@dataclassclassAddress(JsonSchemaMixin):"""Postal Address"""building:strstreet:strcity:str@dataclassclassCompany(JsonSchemaMixin):"""Company Details"""name:straddress: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 usingNewTypefromdataclasses_jsonschemaimportJsonSchemaMixin,FieldEncoderPhoneNumber=NewType('PhoneNumber',str)classPhoneNumberField(FieldEncoder):@propertydefjson_schema(self):return{'type':'string','pattern':r'^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$'}JsonSchemaMixin.register_field_encoders({PhoneNumber:PhoneNumberField()})@dataclassclassPerson(JsonSchemaMixin):name:strphone_number:PhoneNumberFor more examplessee the testsAPISpec PluginNew in v2.5.0OpenAPI & Swagger specs can be generated using the apispec plugin:fromtypingimportOptional,ListfromdataclassesimportdataclassfromapispecimportAPISpecfromapispec_webframeworks.flaskimportFlaskPluginfromflaskimportFlask,jsonifyimportpytestfromdataclasses_jsonschema.apispecimportDataclassesPluginfromdataclasses_jsonschemaimportJsonSchemaMixin# Create an APISpecspec=APISpec(title="Swagger Petstore",version="1.0.0",openapi_version="3.0.2",plugins=[FlaskPlugin(),DataclassesPlugin()],)@dataclassclassCategory(JsonSchemaMixin):"""Pet category"""name:strid:Optional[int]@dataclassclassPet(JsonSchemaMixin):"""A pet"""categories:List[Category]name:strapp=Flask(__name__)@app.route("/random")defrandom_pet():"""A cute furry animal endpoint.
    ---
    get:
      description: Get a random pet
      responses:
        200:
          content:
            application/json:
              schema:
                $ref: Pet
    """pet=get_random_pet()returnjsonify(pet.to_dict())# Dependant schemas (e.g. 'Category') are added automaticallyspec.components.schema("Pet",schema=Pet)withapp.test_request_context():spec.path(view=random_pet)TODOAdd benchmarks against alternatives such aspydanticandmarshmallow