Jsonschema-gen

Quickstart


pypi docs codecov tests code style: black python

jsonschema-gen is Python type hints parser which can convert function and method annotations into JSONSchema objects.

  • Pythonic classes for JSONSchema types

  • Extensive type coverage: TypedDict, Generic, NewType, etc.

  • No external dependencies

Installation

With pip and python 3.8+:

pip3 install jsonschema-gen

How to use

See the user guide for more info.

Create a parser:

from jsonschema_gen import Parser

parser = Parser(strict=True)

Generate schema for your function or method from Python type hints (see the list of supported types):

from typing import NewType

UserName = NewType('UserName', str)

class UserData:
    def get_user(self, name: UserName, active: bool = True) -> dict:
        """Get user by username."""

annotation = parser.parse_function(UserData.get_user, UserData)

The result is an annotation object with input .kwargs and output .returns. You can get a JSONSchema compatible dict using json_repr() on .kwargs:

schema = annotation.kwargs.json_repr()

The result would look like this (if converted to JSON with dumps):

{
  "type": "object",
  "title": "Get user by username.",
  "properties": {
    "name": {
      "title": "Username",
      "type": "string"
    },
    "active": {
      "type": "boolean",
      "default": true
    }
  },
  "required": [
    "name"
  ],
  "additionalProperties": false
}

Use fastjsonschema or other JSONSchema validation library to create a validator for the schema:

from fastjsonschema import compile

validator = compile(schema)
valiator({'name': 'John', 'email': 'john@dowe'})

Alternatively you can pass the whole class to the parser to get the annotation mapping:

annotations = parser.parse_class(UserData)
annotations['get_user'].kwargs.json_repr()

Compatibility

The Python type hints are vast and yet not well organized, so there could always be some data type I forgot to add here. Read the customization guide to extend the standard list of type parsers.

Some annotations cannot be converted to JSONSchema objects, for example: positional-only arguments, variable positionals, etc. There are different strategies considering these types of parameters.

Python 3.8 compatibility is so-so due to lots of features and changes made in 3.9. However, it still should support most of the functionality.

Also read about the strict mode.

License

MIT License

Copyright (c) 2024 violet-black

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.