Pyjo.JSON.Schema - JSON Schema from type hints, and its validation

from Pyjo.JSON.Schema import Schema, z

def weather(city: str, days: int = 3) -> dict[str, float]:
    """Forecast of the weather.

    :param city: Name of the city.
    :param days: Number of days.
    """

print(Schema.parameters(weather).data)
print(Schema.returns(weather).data)

print(z.object(city=z.string().describe('Name of the city'), days=z.int().min(1).optional()).data)

result = Schema.parameters(weather).validate({'city': 'Warsaw', 'days': 'three'})
if not result:
    print(result)

# Or import the module, as in Google Python Style Guide

import Pyjo.JSON.Schema

print(Pyjo.JSON.Schema.of(list[int]).data)
print(Pyjo.JSON.Schema.new({'type': 'string'}).data)

Pyjo.JSON.Schema makes JSON Schema 2020-12 from the type hints of Python, from the annotations of a type or of the parameters and the return value of a function, with the descriptions of its docstring, or builds it with a chain of methods, after zod, so that the schema of a tool of JavaScript ports as it is. Both give an object of Pyjo.JSON.Schema, which holds the schema in data, as Pyjo.JSON encodes it, and so does a schema written by hand.

The types of the type hints, and the schemas that they give:

  • bool, int, float, str and None are boolean, integer, number, string and null, and Any and object are {}, any value;

  • list[T], set[T] and frozenset[T] are an array of items, the sets with uniqueItems, tuple[A, B] an array of prefixItems, and tuple[T, ...] one of items;

  • dict[str, T] is an object of additionalProperties;

  • T | None and Optional[T] add null to the type of a schema that has only a type, and are an anyOf with null otherwise, and other unions are anyOf;

  • Literal is a const or an enum, and so is an enum.Enum of its values, with their type where they have one;

  • a TypedDict is an object whose required are its required keys, closed with closed=True of PEP 728, and a dataclass one whose required are the fields without a default;

  • datetime.datetime, datetime.date, datetime.time, uuid.UUID and Pyjo.URL are a string with the format date-time, date, time, uuid and uri;

  • Annotated[T, ...] adds a string as the description, and the keywords of a dict, as minimum and pattern, or of a schema, as z.email(), without a class of a library of validation;

  • a type alias is its value, and a NewType its type.

A TypedDict, a dataclass, an enum.Enum or a type alias that is used more than once, or a type that refers to itself, goes to $defs, where a $ref refers to it. A schema that refers to itself refers to its root with #, so that the root stays an object, as the inputSchema of a tool of MCP has to be. The description of a TypedDict, a dataclass or an enum.Enum is the first paragraph of its docstring.

A type that has no schema, as bytes, a TypeVar or a class of its own, fails with a Pyjo.Exception that names it and where it is. The annotations are those that typing.get_type_hints() gives, lazy as of PEP 649, or strings with from __future__ import annotations, so a name that the module of a type does not have fails too.

A schema has no $schema, as the schemas of MCP and OpenAPI, whose dialect is known. DIALECT names it on request, with meta().

# {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'type': 'string'}
z.string().meta({'$schema': Pyjo.JSON.Schema.DIALECT}).data

The builder is a subset of zod, what JSON Schema has, without its transformations, refinements, coercions and the types that are inferred from a schema. Its methods are those of zod in the names of Python, multiple_of for multipleOf, and z is the class itself, so that z.object({...}) reads as in JavaScript. An object is as zod gives it for the input, which a tool gets: a property that has a default is not required, and the properties that it does not name are not forbidden, unless the object is strict. Where zod gives another schema of the same, the method says so.

Validation

validate() validates a value, as Pyjo.JSON decodes it, with a schema of any of the three forms, and gives a Result, which is false if the value is not valid, with the errors of the value, each with the JSON Pointer of the value and of the keyword.

# /days: Expected integer - got string.
print(z.object(days=z.int()).validate({'days': 'three'}))

It is the validation of JSON Schema 2020-12 with the keywords that the schema of a tool, of a body of an API or of a configuration has:

  • type, enum and const;

  • minimum, maximum, exclusiveMinimum, exclusiveMaximum and multipleOf of numbers;

  • minLength, maxLength, pattern and format of strings;

  • items, prefixItems, minItems, maxItems, uniqueItems, contains, minContains and maxContains of arrays;

  • properties, required, additionalProperties, patternProperties, propertyNames, minProperties, maxProperties, dependentRequired and dependentSchemas of objects;

  • allOf, anyOf, oneOf, not, if, then and else;

  • $ref to the schemas of the document, by a JSON Pointer, as to $defs, by their $anchor and by the $id of a schema in the schema, also to itself, and to the schemas of the registry of add_schema(), which it never downloads.

The keywords of 2020-12 that it does not support, $dynamicRef, unevaluatedItems and unevaluatedProperties, and a $schema of another dialect, fail with a Pyjo.Exception, as a $ref to a schema that it does not have does, and a keyword that 2020-12 does not have, as additionalItems of the older drafts, is ignored, as the specification says of a keyword that it does not know. The annotations, as title, default and contentMediaType, validate nothing.

The values are those of JSON: bool is not an integer nor a number, a float without a fraction is an integer, 1 and 1.0 are equal for enum, const and uniqueItems, True and 1 are not, and a tuple is an array. A value that JSON does not have, as bytes, a set, nan or a name of a property that is not a string, is an error of its own, whatever the schema.

format is an annotation, as JSON Schema has it by default, and an assertion with formats, for the formats date-time, date, time and duration of RFC 3339, email, hostname, ipv4, ipv6, uri, uri-reference, uuid, regex, json-pointer and relative-json-pointer. Another format, as idn-email, iri or uri-template, stays an annotation.

A pattern is a regular expression of ECMAScript, which is one of re with these translations: \d, \w and \b are of ASCII, \s is the white space of ECMAScript, . matches no line terminator, $ matches only at the end, a named group is (?<name>...) and its backreference \k<name>, \p{...} is a general category of Unicode, or ASCII, Any and Assigned, and \cX, \u{...}, [] and [^] are as ECMAScript has them. What re does not have, as a lookbehind of a variable width or \p{Script=...}, and the syntax of Python that ECMAScript does not have, as (?P<name>...), fail with a Pyjo.Exception.

See also

Pyjo.JSON, Pyjo.JSON.Pointer, https://mojolicious.org.

It has no counterpart in Mojolicious, it is written from the specification of JSON Schema 2020-12, its builder is inspired by zod, and its validation is tested with the official test suite of JSON Schema, JSON-Schema-Test-Suite.

Classes

Pyjo.JSON.Schema.DIALECT = 'https://json-schema.org/draft/2020-12/schema'

The dialect of the schemas, JSON Schema 2020-12, as $schema names it.

class Pyjo.JSON.Schema.Error(path: str = '', keyword_path: str = '', message: str = '')[source]

An error of a value, which validate() gives, with where it is in the value and in the schema.

# "/days: Expected integer - got string."
str(error)
__init__(path: str = '', keyword_path: str = '', message: str = '') → None[source]
__json__() → dict[str, str][source]
data = error.__json__()

The error as Pyjo.JSON encodes it, with path, keyword_path and message.

__repr__() → str[source]

Return repr(self).

__str__() → str[source]
string = str(error)

The path, with / for the whole value, and the message.

keyword_path
keyword_path = error.keyword_path

The JSON Pointer of the keyword in the schema, through the $ref that the validation follows, as /properties/days/type.

message
message = error.message

What is wrong with the value.

path
path = error.path

The JSON Pointer of the value in the validated value, as Pyjo.JSON.Pointer takes it, or of the missing property of required.

class Pyjo.JSON.Schema.Pyjo_JSON_Schema(data: dict[str, Any] | bool | None = None)[source]

Pyjo.JSON.Schema inherits all methods from Pyjo.Base and implements the following new ones.

__init__(data: dict[str, Any] | bool | None = None) → None[source]
schema = Pyjo.JSON.Schema.new()
schema = Pyjo.JSON.Schema.new({'type': 'string', 'minLength': 1})

Build new Pyjo.JSON.Schema object, of a schema written by hand, which can hold other objects of Pyjo.JSON.Schema, or of any value without arguments.

__json__() → dict[str, Any] | bool[source]
data = schema.__json__()

The schema as Pyjo.JSON encodes it, data.

__repr__() → str[source]

Return repr(self).

add_schema(schema: Pyjo_JSON_Schema | dict[str, Any] | bool, uri: str | None = None) → Self[source]
schema = schema.add_schema({'$id': 'https://example.com/address', 'type': 'object'})
schema = schema.add_schema(z.string(), 'https://example.com/name')

Add a schema to the registry of the schema, under its $id or the URI, where a $ref of the schema finds it, and its $id and $anchor too.

classmethod any() → Self[source]
schema = z.any()

The schema of any value, {}.

classmethod array(element: Any = None) → Self[source]
schema = z.array(z.string())

The schema of an array of elements, of any value without them.

# {'type': 'array', 'items': {'type': 'string'}, 'minItems': 1}
z.array(z.string()).nonempty().data
classmethod boolean() → Self[source]
schema = z.boolean()

The schema of true or false.

property data: dict[str, Any] | bool[source]
data = schema.data

The schema as a dict, with $defs for the types that are used more than once or refer to themselves, or True or False for a schema of any value or of none.

# {'type': 'array', 'items': {'type': 'integer'}}
Pyjo.JSON.Schema.of(list[int]).data
date() → Self[source]
schema = schema.date()

A string of the format date, as z.iso.date().

datetime() → Self[source]
schema = schema.datetime()

A string of the format date-time, as z.iso.datetime(). zod also gives the pattern of its own regular expression.

default(value: Any) → Self[source]
schema = schema.default(3)

The value of a property that is not given, default, which an object does not require, as zod has it for the input.

describe(description: str) → Self[source]
schema = schema.describe('Name of the city')

The description of the value, description.

email() → S[source]
schema = z.email()
schema = z.string().email()

A string of the format email. zod also gives the pattern of its own regular expression.

classmethod enum(values: Iterable[Any] | type[_Enum]) → Self[source]
schema = z.enum(['celsius', 'fahrenheit'])
schema = z.enum(Unit)

The schema of one of the values, or of the values of an enum.Enum, as enum, with their type where they have one.

# {'type': 'string', 'enum': ['celsius', 'fahrenheit']}
z.enum(['celsius', 'fahrenheit']).data
gt(value: float) → Self[source]
schema = schema.gt(0)

A number greater than the value, exclusiveMinimum.

gte(value: float) → Self[source]
schema = schema.gte(1)

The same as min().

classmethod int() → Self[source]
schema = z.int()

The schema of an integer. zod also gives the least and the greatest safe integer of JavaScript as its minimum and maximum, which an integer of Python does not have.

# {'type': 'integer', 'minimum': 1, 'maximum': 7}
z.int().min(1).max(7).data
property is_lazy: bool[source]
boolean = schema.is_lazy

True if the schema is the one that a function gives, as lazy() makes it.

property is_optional: bool[source]
boolean = schema.is_optional

True if the schema is of a property that an object does not require, as optional() and default() make it.

iso: _ISO
schema = z.iso.datetime()
schema = z.iso.date()
schema = z.iso.time()

The schemas of the strings of the formats date-time, date and time, as datetime(), date() and time() of a string.

property keywords: dict[str, Any] | bool[source]
keywords = schema.keywords

The keywords of the schema, which can hold other objects of Pyjo.JSON.Schema, as data has them without them.

classmethod lazy(getter: Callable[[], Any]) → Self[source]
schema = z.lazy(lambda: category)

The schema that a function gives when data is made, so that a schema can refer to itself, or to another one that is made after it.

category = z.object(name=z.string(), subcategories=z.array(z.lazy(lambda: category)))

# {'type': 'object',
#  'properties': {'name': {'type': 'string'},
#                 'subcategories': {'type': 'array', 'items': {'$ref': '#'}}},
#  'required': ['name', 'subcategories']}
category.data
length(value: int) → Self[source]
schema = schema.length(3)

The length of a string, or the number of elements of an array.

classmethod literal(value: Any) → Self[source]
schema = z.literal('celsius')
schema = z.literal(['celsius', 'fahrenheit'])

The schema of a value, as const, or of one of a list of values, as enum, with their type where they have one.

# {'type': 'string', 'const': 'celsius'}
z.literal('celsius').data
loose() → Self[source]
schema = schema.loose()

An object that allows other properties, additionalProperties: {}.

classmethod loose_object(shape: dict[str, Any] | None = None, /, **kwargs: Any) → Self[source]
schema = z.loose_object({'city': z.string()})

The schema of an object that allows other properties, object() and loose().

lt(value: float) → Self[source]
schema = schema.lt(10)

A number less than the value, exclusiveMaximum.

lte(value: float) → Self[source]
schema = schema.lte(5)

The same as max().

max(value: float) → Self[source]
schema = schema.max(5)

The greatest length of a string, the greatest value of a number, or the greatest number of elements of an array, as maxLength, maximum and maxItems.

meta(keywords: dict[str, Any] | None = None, /, **kwargs: Any) → Self[source]
schema = schema.meta({'$schema': Pyjo.JSON.Schema.DIALECT})
schema = schema.meta(title='City', examples=['Warsaw'])

Other keywords of the schema. zod keeps them as the metadata of the schema too.

min(value: float) → Self[source]
schema = schema.min(1)

The least length of a string, the least value of a number, or the least number of elements of an array, as minLength, minimum and minItems.

multiple_of(value: float) → Self[source]
schema = schema.multiple_of(2)

A number that is a multiple of the value, multipleOf.

name: str | None
name = schema.name
schema.name = 'Category'

The name of the schema in $defs, where it goes when a schema holds it more than once, as the name of its type, or Schema and a number without a name.

nonempty() → Self[source]
schema = schema.nonempty()

A string or an array that is not empty, min() of 1.

classmethod null() → Self[source]
schema = z.null()

The schema of null.

nullable() → Self[source]
schema = schema.nullable()

The schema of the value or of null, in its type where the schema has only a type, and in anyOf otherwise.

# {'type': ['string', 'null']}
z.string().nullable().data
nullish() → Self[source]
schema = schema.nullish()

nullable() and optional().

classmethod number() → Self[source]
schema = z.number()

The schema of a number.

# {'type': 'number', 'exclusiveMinimum': 0}
z.number().gt(0).data
classmethod object(shape: dict[str, Any] | None = None, /, **kwargs: Any) → Self[source]
schema = z.object({'city': z.string(), 'days': z.int().optional()})
schema = z.object(city=z.string(), days=z.int().optional())

The schema of an object of the properties, which it requires, but the optional ones, as optional() and default() make them. A name that is a keyword of Python, or not a name of Python, goes in the dict. zod also gives additionalProperties: false for the output, and this is the schema of the input, which a tool gets.

# {'type': 'object', 'properties': {'class': {'type': 'string'}}, 'required': ['class']}
z.object({'class': z.string()}).data
classmethod of(tp: Any) → Self[source]
schema = Pyjo.JSON.Schema.of(list[int])
schema = Pyjo.JSON.Schema.of(Point)

The schema of a type of the type hints, or the schema itself, or a schema written by hand as a dict.

# {'type': ['string', 'null']}
Pyjo.JSON.Schema.of(str | None).data

# {'type': 'object', 'additionalProperties': {'type': 'number'}}
Pyjo.JSON.Schema.of(dict[str, float]).data
optional() → Self[source]
schema = schema.optional()

The schema of a property that an object does not require.

# {'type': 'object', 'properties': {'days': {'type': 'integer'}}}
z.object(days=z.int().optional()).data
classmethod parameters(function: Callable[[...], Any], skip: int = 0) → Self[source]
schema = Pyjo.JSON.Schema.parameters(tool)
schema = Pyjo.JSON.Schema.parameters(tool, skip=1)

The schema of the parameters of a function, as the inputSchema of a tool, an object whose properties are the parameters, with the ones without a default required, and the first paragraph of its docstring as its description. The description of a parameter is the one of the field :param x: of its docstring, in reStructuredText, or of the section Args: of the Google Python Style Guide.

skip leaves out the first parameters, as the context or the controller that a tool or an action gets before its arguments; self of a bound method is already gone. **kwargs: T gives the additionalProperties of the schema of T, and without it the object has no other properties. A parameter without an annotation is of any value. *args and a parameter that is only positional fail, as an object of JSON has no members without a name.

def weather(c, city: str, days: int = 3):
    """Forecast of the weather.

    Args:
        city: Name of the city.
    """

# {'type': 'object', 'description': 'Forecast of the weather.',
#  'properties': {'city': {'type': 'string', 'description': 'Name of the city.'},
#                 'days': {'type': 'integer', 'default': 3}},
#  'required': ['city'], 'additionalProperties': False}
Pyjo.JSON.Schema.parameters(weather, skip=1).data
parse(value: Any, formats: bool = False) → Any[source]
value = schema.parse({'city': 'Warsaw'})

The value, if the schema validates it, as validate() does, or a Pyjo.Exception with the errors, one in each line.

passthrough() → Self[source]
schema = schema.passthrough()

The same as loose().

classmethod record(key: Any, value: Any = None) → Self[source]
schema = z.record(z.string(), z.int())
schema = z.record(z.int())

The schema of an object whose properties are all of a value, with the schema of their names where it is not any string. zod also gives propertyNames: {'type': 'string'}, which every name of JSON is.

# {'type': 'object', 'additionalProperties': {'type': 'integer'}}
z.record(z.string(), z.int()).data
regex(pattern: str | Pattern[str]) → Self[source]
schema = schema.regex(r'^[a-z]+$')
schema = schema.regex(re.compile(r'^[a-z]+$'))

A string that matches a regular expression, pattern, which JSON Schema has in the syntax of ECMAScript.

resolve() → Pyjo_JSON_Schema[source]
schema = schema.resolve()

The schema that the function of a lazy schema gives, or the schema itself.

classmethod returns(function: Callable[[...], Any]) → Self | None[source]
schema = Pyjo.JSON.Schema.returns(tool)

The schema of the return value of a function, as the outputSchema of a tool, with the description of the field :returns: of its docstring, or of its section Returns:, or None for a function without the annotation of its return value.

def forecast(city: str) -> list[float]:
    """Temperatures.

    :returns: One for each day.
    """

# {'type': 'array', 'items': {'type': 'number'}, 'description': 'One for each day.'}
Pyjo.JSON.Schema.returns(forecast).data
strict() → Self[source]
schema = schema.strict()

An object without other properties, additionalProperties: false.

classmethod strict_object(shape: dict[str, Any] | None = None, /, **kwargs: Any) → Self[source]
schema = z.strict_object({'city': z.string()})

The schema of an object without other properties, object() and strict().

classmethod string() → Self[source]
schema = z.string()

The schema of a string.

# {'type': 'string', 'minLength': 1, 'maxLength': 5}
z.string().min(1).max(5).data
time() → Self[source]
schema = schema.time()

A string of the format time, as z.iso.time(). zod gives only the pattern of its own regular expression.

classmethod tuple(elements: Iterable[Any], rest: Any = None) → Self[source]
schema = z.tuple([z.string(), z.int()])
schema = z.tuple([z.string()], z.int())

The schema of an array of the elements, each of its own, and of the elements of rest after them, if any. zod also gives items: false to a tuple without rest, which maxItems already says.

# {'type': 'array', 'prefixItems': [{'type': 'string'}, {'type': 'integer'}],
#  'minItems': 2, 'maxItems': 2}
z.tuple([z.string(), z.int()]).data
classmethod union(options: Iterable[Any]) → Self[source]
schema = z.union([z.string(), z.int()])

The schema of a value of one of the options, as anyOf.

url() → S[source]
schema = z.url()
schema = z.string().url()

A string of the format uri.

uuid() → S[source]
schema = z.uuid()
schema = z.string().uuid()

A string of the format uuid. zod also gives the pattern of its own regular expression.

validate(value: Any, formats: bool = False) → Result[source]
result = schema.validate({'city': 'Warsaw'})
result = schema.validate({'date': '2026-10-23'}, formats=True)

Validate a value, as Pyjo.JSON decodes it, and return a Result, which is true if the value is valid, with the Error objects of the value otherwise. format is an annotation, as JSON Schema has it by default, and an assertion with formats.

# "/days: Expected integer - got string."
str(z.object(days=z.int()).validate({'days': 'three'}))
class Pyjo.JSON.Schema.Result(errors: Iterable[Error] = ())[source]

The result of validate(), which is true if the value is valid, as the assertions of Pyjo.Test are.

result = schema.validate(value)
if not result:
    for error in result.errors:
        print(error.path, error.message)
__bool__() → bool[source]
boolean = bool(result)

The value of is_valid.

__init__(errors: Iterable[Error] = ()) → None[source]
__json__() → dict[str, Any][source]
data = result.__json__()

The result as Pyjo.JSON encodes it, valid and the errors.

__repr__() → str[source]

Return repr(self).

__str__() → str[source]
string = str(result)

The errors, one in each line, or an empty string if the value is valid.

errors: Pyjo_Collection[Error]
errors = result.errors

The Error objects of the value, in a Pyjo.Collection, empty if the value is valid.

property is_valid: bool[source]
boolean = result.is_valid

True if the value is valid, without errors.

Pyjo.JSON.Schema.of(tp: Any) → Self[source]
schema = Pyjo.JSON.Schema.of(list[int])
schema = Pyjo.JSON.Schema.of(Point)

The schema of a type of the type hints, or the schema itself, or a schema written by hand as a dict.

# {'type': ['string', 'null']}
Pyjo.JSON.Schema.of(str | None).data

# {'type': 'object', 'additionalProperties': {'type': 'number'}}
Pyjo.JSON.Schema.of(dict[str, float]).data
Pyjo.JSON.Schema.parameters(function: Callable[[...], Any], skip: int = 0) → Self[source]
schema = Pyjo.JSON.Schema.parameters(tool)
schema = Pyjo.JSON.Schema.parameters(tool, skip=1)

The schema of the parameters of a function, as the inputSchema of a tool, an object whose properties are the parameters, with the ones without a default required, and the first paragraph of its docstring as its description. The description of a parameter is the one of the field :param x: of its docstring, in reStructuredText, or of the section Args: of the Google Python Style Guide.

skip leaves out the first parameters, as the context or the controller that a tool or an action gets before its arguments; self of a bound method is already gone. **kwargs: T gives the additionalProperties of the schema of T, and without it the object has no other properties. A parameter without an annotation is of any value. *args and a parameter that is only positional fail, as an object of JSON has no members without a name.

def weather(c, city: str, days: int = 3):
    """Forecast of the weather.

    Args:
        city: Name of the city.
    """

# {'type': 'object', 'description': 'Forecast of the weather.',
#  'properties': {'city': {'type': 'string', 'description': 'Name of the city.'},
#                 'days': {'type': 'integer', 'default': 3}},
#  'required': ['city'], 'additionalProperties': False}
Pyjo.JSON.Schema.parameters(weather, skip=1).data
Pyjo.JSON.Schema.returns(function: Callable[[...], Any]) → Self | None[source]
schema = Pyjo.JSON.Schema.returns(tool)

The schema of the return value of a function, as the outputSchema of a tool, with the description of the field :returns: of its docstring, or of its section Returns:, or None for a function without the annotation of its return value.

def forecast(city: str) -> list[float]:
    """Temperatures.

    :returns: One for each day.
    """

# {'type': 'array', 'items': {'type': 'number'}, 'description': 'One for each day.'}
Pyjo.JSON.Schema.returns(forecast).data