OpenAPI Schema to JSON Schema Converter
This Python library provides a utility to convert OpenAPI 3.0 Schema Objects into compatible JSON Schema Draft 4 representations. It addresses key discrepancies between the two specifications, such as `nullable` handling and removal of OpenAPI-specific keywords, to enable validation with standard JSON Schema validators. This package is a direct Python port of the JavaScript library `mikunn/openapi-schema-to-json-schema` (v2.1.0).
Warnings
- gotcha The library does not dereference `$ref` fields within the OpenAPI schema. If your schema uses `$ref`s, you must resolve them using another tool or library before passing the schema to `to_json_schema`.
- gotcha This library converts OpenAPI 3.0 schemas to JSON Schema Draft 4. It does not support newer JSON Schema drafts (e.g., Draft 2019-09, 2020-12) or OpenAPI 3.1, which aligns with newer JSON Schema versions. Using it for newer standards may lead to incompatible or incomplete conversions.
- gotcha By default, several OpenAPI-specific keywords (e.g., `discriminator`, `readOnly`, `writeOnly`, `xml`, `externalDocs`, `example`, `deprecated`) are removed from the resulting JSON Schema as they are not standard in JSON Schema Draft 4. The `nullable` keyword is converted into a `type` array that includes `"null"`.
Install
-
pip install py-openapi-schema-to-json-schema
Imports
- to_json_schema
from openapi_schema_to_json_schema import to_json_schema
Quickstart
import json
from openapi_schema_to_json_schema import to_json_schema
openapi_schema = {
"type": "object",
"properties": {
"name": {
"type": "string",
"nullable": True,
}
},
"x-patternProperties": {
"^[a-z]+$": {
"type": "number",
}
}
}
# Options can be passed to control conversion behavior
# For example, to enable conversion of 'x-patternProperties' to 'patternProperties'
options = {"supportPatternProperties": True}
converted_schema = to_json_schema(openapi_schema, options)
print(json.dumps(converted_schema, indent=2))