JSON Schema documents across dialects (Effect's JsonSchema).
Every conversion goes through Draft 2020-12: read a schema with one of the
from_schema_* functions into a Document (the root schema and its
definitions, kept apart), then write it out with to_document_draft_07,
to_document_draft_04 or to_multi_document_open_api_3_1::
from pyfect import json_schema
doc = json_schema.from_schema_draft_07({"type": "array", "items": [{"type": "string"}]})
doc.schema # {"type": "array", "prefixItems": [{"type": "string"}]}
json_schema.to_document_draft_07(doc).schema # back to Draft-07References ($ref) are relocated to where their targets land, schema
resources ($id) included. A keyword that cannot be carried over without
changing what the schema accepts raises ValueError with Effect's message.
Schemas are plain dicts; inputs are never mutated.
Values#
| Attribute | Type | Description |
|---|---|---|
META_SCHEMA_URI_DRAFT_04 | Literal['http://json-schema.org/draft-04/schema#'] = 'http://json-schema.org/draft-04/schema#' | |
META_SCHEMA_URI_DRAFT_07 | Literal['http://json-schema.org/draft-07/schema#'] = 'http://json-schema.org/draft-07/schema#' | |
META_SCHEMA_URI_DRAFT_2020_12 | Literal['https://json-schema.org/draft/2020-12/schema'] = 'https://json-schema.org/draft/2020-12/schema' | |
VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP | Pattern[str] | The keys OpenAPI allows under |
Types#
| Type | Definition | Description |
|---|---|---|
Definitions | type Definitions = dict[str, JsonSchema] | Named schemas, referenced as |
Dialect | type Dialect = Literal['draft-04', 'draft-07', 'draft-2020-12', 'openapi-3.1', 'openapi-3.0'] | |
JsonSchema | type JsonSchema = dict[str, object] | One JSON Schema node: any keyword to any value. |
Type | type Type = Literal['string', 'number', 'boolean', 'array', 'object', 'null', 'integer'] | The JSON Schema |
Classes#
Functions#
from_schema_draft_07#
from_schema_draft_07(js) -> Document[Draft2020]A Draft-07 schema in Draft 2020-12: tuple items as
prefixItems, definitions as $defs, dependencies split,
$id fragments as $anchor, references relocated. A keyword that
would gain a meaning in Draft 2020-12 raises ValueError.
| Parameter | Type | Description |
|---|---|---|
js | JsonSchema |
Returns Document[Draft2020]
def from_schema_draft_07(js: JsonSchema) -> Document[Draft2020]:
"""A Draft-07 schema in Draft 2020-12: tuple ``items`` as
``prefixItems``, ``definitions`` as ``$defs``, ``dependencies`` split,
``$id`` fragments as ``$anchor``, references relocated. A keyword that
would gain a meaning in Draft 2020-12 raises ``ValueError``."""
return from_schema_draft_2020_12(from_draft_07(js))from_schema_draft_2020_12#
from_schema_draft_2020_12(js) -> Document[Draft2020]A Draft 2020-12 schema as a document: its $defs become the
definitions (an empty dict when there are none).
| Parameter | Type | Description |
|---|---|---|
js | JsonSchema |
Returns Document[Draft2020]
def from_schema_draft_2020_12(js: JsonSchema) -> Document[Draft2020]:
"""A Draft 2020-12 schema as a document: its ``$defs`` become the
definitions (an empty dict when there are none)."""
schema = {key: value for key, value in js.items() if key != "$defs"}
defs = js.get("$defs")
definitions = cast("Definitions", dict(as_object(defs))) if is_object(defs) else {}
return Document("draft-2020-12", schema, definitions)from_schema_open_api_3_0#
from_schema_open_api_3_0(js) -> Document[Draft2020]An OpenAPI 3.0 schema in Draft 2020-12: nullable as a null
type or branch, boolean exclusive bounds as numeric ones, example as
examples.
| Parameter | Type | Description |
|---|---|---|
js | JsonSchema |
Returns Document[Draft2020]
def from_schema_open_api_3_0(js: JsonSchema) -> Document[Draft2020]:
"""An OpenAPI 3.0 schema in Draft 2020-12: ``nullable`` as a ``null``
type or branch, boolean exclusive bounds as numeric ones, ``example`` as
``examples``."""
return from_schema_draft_2020_12(from_open_api_3_0(js))from_schema_open_api_3_1#
from_schema_open_api_3_1(js) -> Document[Draft2020]An OpenAPI 3.1 schema in Draft 2020-12: #/components/schemas/X
references as #/$defs/X, example folded into examples.
| Parameter | Type | Description |
|---|---|---|
js | JsonSchema |
Returns Document[Draft2020]
def from_schema_open_api_3_1(js: JsonSchema) -> Document[Draft2020]:
"""An OpenAPI 3.1 schema in Draft 2020-12: ``#/components/schemas/X``
references as ``#/$defs/X``, ``example`` folded into ``examples``."""
return from_schema_draft_2020_12(from_open_api_3_1(js))to_document_draft_04#
to_document_draft_04(document) -> Document[Literal['draft-04']]The document in Draft-04: boolean schemas as {} / {"not": {}},
conditionals and contains lowered to anyOf / allOf / not,
const as enum. A keyword Draft-04 cannot express raises
ValueError.
| Parameter | Type | Description |
|---|---|---|
document | Document[Draft2020] |
Returns Document[Literal['draft-04']]
def to_document_draft_04(document: Document[Draft2020]) -> Document[Literal["draft-04"]]:
"""The document in Draft-04: boolean schemas as ``{}`` / ``{"not": {}}``,
conditionals and ``contains`` lowered to ``anyOf`` / ``allOf`` / ``not``,
``const`` as ``enum``. A keyword Draft-04 cannot express raises
``ValueError``."""
schema, definitions = _convert_document(document, to_draft_04, boolean_adapter=_boolean_schema)
return Document("draft-04", schema, definitions)to_document_draft_07#
to_document_draft_07(document) -> Document[Literal['draft-07']]The document in Draft-07. A keyword Draft-07 cannot express raises
ValueError.
| Parameter | Type | Description |
|---|---|---|
document | Document[Draft2020] |
Returns Document[Literal['draft-07']]
def to_document_draft_07(document: Document[Draft2020]) -> Document[Literal["draft-07"]]:
"""The document in Draft-07. A keyword Draft-07 cannot express raises
``ValueError``."""
return to_document_draft_07_with_definitions_path(document)to_document_draft_07_with_definitions_path#
to_document_draft_07_with_definitions_path(document, definitions_path=None) -> Document[Literal['draft-07']]The document in Draft-07 with its definitions located at definitions_path,
such as ["components", "schemas"] after to_multi_document_components, so
references into them stay in place (Effect's toDocumentDraft07WithDefinitionsPath);
by default $defs become definitions.
| Parameter | Type | Description |
|---|---|---|
document | Document[Draft2020] | |
definitions_path | Sequence[str] | None = None |
Returns Document[Literal['draft-07']]
def to_document_draft_07_with_definitions_path(
document: Document[Draft2020], definitions_path: Sequence[str] | None = None
) -> Document[Literal["draft-07"]]:
"""The document in Draft-07 with its definitions located at ``definitions_path``,
such as ``["components", "schemas"]`` after ``to_multi_document_components``, so
references into them stay in place (Effect's ``toDocumentDraft07WithDefinitionsPath``);
by default ``$defs`` become ``definitions``."""
schema, definitions = _convert_document(
document, to_draft_07, definitions_path=definitions_path
)
return Document("draft-07", schema, definitions)to_multi_document_open_api_3_1#
to_multi_document_open_api_3_1(multi_document) -> MultiDocument[Literal['openapi-3.1']]The documents with their shared definitions as OpenAPI 3.1
components.schemas: references rewritten, keys OpenAPI forbids
sanitized (_1, _2... on a collision).
| Parameter | Type | Description |
|---|---|---|
multi_document | MultiDocument[Draft2020] |
Returns MultiDocument[Literal['openapi-3.1']]
def to_multi_document_open_api_3_1(
multi_document: MultiDocument[Draft2020],
) -> MultiDocument[Literal["openapi-3.1"]]:
"""The documents with their shared definitions as OpenAPI 3.1
``components.schemas``: references rewritten, keys OpenAPI forbids
sanitized (``_1``, ``_2``... on a collision)."""
return to_open_api_3_1(multi_document)get_reference_key#
get_reference_key(ref) -> str | NoneThe definition name of a #/$defs/<name> reference, else None.
| Parameter | Type | Description |
|---|---|---|
ref | str |
Returns str | None
def get_reference_key(ref: str) -> str | None:
"""The definition name of a ``#/$defs/<name>`` reference, else ``None``."""
path = parse_uri_fragment(ref) if ref.startswith("#") else None
return path[1] if path is not None and len(path) == 2 and path[0] == "$defs" else Nonerewrite_refs#
rewrite_refs(schema, rewrite) -> JsonSchemaA copy of schema with every $ref and $dynamicRef replaced
by rewrite(ref).
| Parameter | Type | Description |
|---|---|---|
schema | Mapping[str, object] | |
rewrite | Callable[[str], str] |
Returns JsonSchema
def rewrite_refs(schema: Mapping[str, object], rewrite: Callable[[str], str]) -> JsonSchema:
"""A copy of ``schema`` with every ``$ref`` and ``$dynamicRef`` replaced
by ``rewrite(ref)``."""
return cast(
"JsonSchema",
transform_schema(schema, lambda node, _: rewrite_schema_ref(node, lambda r, _: rewrite(r))),
)sanitize_open_api_components_schemas_key#
sanitize_open_api_components_schemas_key(key) -> strkey with every character OpenAPI forbids in a
components.schemas key replaced by _ ("_" for "").
| Parameter | Type | Description |
|---|---|---|
key | str |
Returns str
def sanitize_open_api_components_schemas_key(key: str) -> str:
"""``key`` with every character OpenAPI forbids in a
``components.schemas`` key replaced by ``_`` (``"_"`` for ``""``)."""
return re.sub(r"[^a-zA-Z0-9._-]", "_", key) if key else "_"to_multi_document_components#
to_multi_document_components(multi_document, *, target, check_schema=None) -> MultiDocument[Literal['draft-2020-12']]The documents with their shared definitions moved under components.schemas
(Effect's toMultiDocumentComponents): references rewritten, keys OpenAPI forbids
sanitized (_1, _2... on a collision), each schema node first given to
check_schema. A schema resource referencing the shared pool raises ValueError
naming target.
| Parameter | Type | Description |
|---|---|---|
multi_document | MultiDocument[Literal['draft-2020-12']] | |
target | str | |
check_schema | Callable[[JsonSchema], None] | None = None |
Returns MultiDocument[Literal['draft-2020-12']]
def to_multi_document_components(
multi_document: MultiDocument[Literal["draft-2020-12"]],
*,
target: str,
check_schema: Callable[[JsonSchema], None] | None = None,
) -> MultiDocument[Literal["draft-2020-12"]]:
"""The documents with their shared definitions moved under ``components.schemas``
(Effect's ``toMultiDocumentComponents``): references rewritten, keys OpenAPI forbids
sanitized (``_1``, ``_2``... on a collision), each schema node first given to
``check_schema``. A schema resource referencing the shared pool raises ``ValueError``
naming ``target``."""
definitions = multi_document.definitions
key_map = _component_keys(list(definitions))
def rewrite(schema: JsonSchema, reject_shared_definition_refs: bool = False) -> JsonSchema:
is_root_resource = creates_resource(schema.get("$id"))
local = schema.get("$defs")
local_definitions = as_object(local) if is_object(local) else None
def transform(node: JsonSchema, in_embedded_resource: bool) -> None:
if check_schema is not None:
check_schema(node)
def rewrite_ref(reference: str, keyword: str) -> str:
path = parse_uri_fragment(reference) if reference.startswith("#") else None
if path is None or len(path) < 2 or path[0] != "$defs":
return reference
key = path[1]
if is_root_resource:
if (
reject_shared_definition_refs
and not in_embedded_resource
and key in definitions
and (local_definitions is None or key not in local_definitions)
):
raise unsupported(
keyword,
target,
"a schema resource cannot reference the shared definitions pool",
)
return reference
if in_embedded_resource:
return reference
return format_uri_fragment(
["components", "schemas", key_map.get(key, key), *path[2:]]
)
rewrite_schema_ref(node, rewrite_ref)
return cast("JsonSchema", transform_schema(schema, transform))
schemas = tuple(rewrite(schema, True) for schema in multi_document.schemas)
out: Definitions = {key_map.get(key, key): rewrite(value) for key, value in definitions.items()}
return MultiDocument("draft-2020-12", schemas, out)On This Page
ValuesTypesClassesFunctionsfrom_schema_draft_07from_schema_draft_2020_12from_schema_open_api_3_0from_schema_open_api_3_1to_document_draft_04to_document_draft_07to_document_draft_07_with_definitions_pathto_multi_document_open_api_3_1get_reference_keyrewrite_refssanitize_open_api_components_schemas_keyto_multi_document_components