Skip to main content

Tool to generate Python types based on TypedDict from a JSON Schema

Project description

JSON Schema generate Python types

Tools to generate Python types based on TypedDict from a JSON schema

Quick start

install:

python3 -m pip install --user jsonschema-gentypes

Convert a JSON schema to a Python file contains the types:

jsonschema-gentypes --json-schema=<JSON schema> --python=<destination Python file>

Config file

You can also write a config file named jsonschema-gentypes.yaml with:

headers: >
  # Automatically generated file from a JSON schema
# Used to correctly format the generated file
callbacks:
  - - black
  - - isort
generate:
  - # JSON schema file path
    source: jsonschema_gentypes/schema.json
    # Python file path
    destination: jsonschema_gentypes/configuration.py
    # The name of the root element
    root_name: Config
    # Argument passed to the API
    api_arguments:
      additional_properties: Only explicit
    # Rename an element
    name_mapping: {}
    # The minimum Python version that the code should support. By default the
    # currently executing Python version is chosen. Note that the output
    # may require typing_extensions to be installed.
    python_version: '3.11'

And just run:

jsonschema-gentypes

Default

The default values are exported in the Python file, then you can do something like that:

value_with_default = my_object.get('field_name', my_schema.FIELD_DEFAULT)

Limitations

Requires Python 3.8

See the issues with label "limitation".

Pre-commit hooks

This project provides pre-commit hooks to automatically generate the files.

repos:
  - repo: https://github.com/camptocamp/jsonschema-gentypes
    rev: <version> # Use the ref you want to point at
    hools:
      - id: jsonschema-gentypes
        files: |
          (?x)^(
              jsonschema-gentypes\.yaml|
              <schema_path>\.json
          )$

See also the pre_commit section in the configuration to run the pre-commit just after the generation, for example with:

pre_commit:
  enabled: true
  arguments:
    - --color=never

OpenAPI3

We can also generate types for OpenAPI3 schemas (automatically detected).

The result of our example in tests/openapi3.json can be used in pyramid with for example:

import pyramid.request
from pyramid.view import view_config
from openaoi3 import *

def open_api(func):
    def wrapper(request: pyramid.request.Request, **kwargs) -> Any:
        typed_request = {}
        try:
            typed_request{'request_body'} = request.json
        except Exception as e:
            pass
        typed_request{'path'} = request.matchdict
        typed_request{'query'} = request.params

        return = func(request, request_typed=typed_request, **kwargs)

    return wrapper


@view_config(route_name="route_name", renderer="json")
@open_api
def view(
  request: pyramid.request.Request,
  request_typed: OgcapiCollectionsCollectionidGet,
) -> OgcapiCollectionsCollectionidGetResponse:
    return {...}

Contributing

Install the pre-commit hooks:

pip install pre-commit
pre-commit install --allow-missing-config

The prospector tests should pass.

The code should be typed.

The code should be tested with pytests.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jsonschema_gentypes-2.4.0.tar.gz (26.6 kB view details)

Uploaded Source

Built Distribution

jsonschema_gentypes-2.4.0-py3-none-any.whl (42.4 kB view details)

Uploaded Python 3

File details

Details for the file jsonschema_gentypes-2.4.0.tar.gz.

File metadata

  • Download URL: jsonschema_gentypes-2.4.0.tar.gz
  • Upload date:
  • Size: 26.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.12

File hashes

Hashes for jsonschema_gentypes-2.4.0.tar.gz
Algorithm Hash digest
SHA256 c01ddbcff39968e65eda9498a264ff4bb396b5018ba872c04b430f1c7dc3e84d
MD5 998bae4a0e811e0508da43527ad1fde7
BLAKE2b-256 d72b1f734131e4b973a36510e90917fcebffc7176d3dbe59b5fc7abda8d56d19

See more details on using hashes here.

Provenance

File details

Details for the file jsonschema_gentypes-2.4.0-py3-none-any.whl.

File metadata

File hashes

Hashes for jsonschema_gentypes-2.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5c4fdeee656bc92da09c24968d6e2c43a8a97e93c5f52a3d816e71b5bdf492bd
MD5 77897eb047b0c167e1d75aea31fa80ad
BLAKE2b-256 635264db08b8affde526bf29285df49793d7d31458318f04b7e6ccf7d7a69827

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page