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,strandNoneareboolean,integer,number,stringandnull, andAnyandobjectare{}, any value;list[T],set[T]andfrozenset[T]are anarrayofitems, the sets withuniqueItems,tuple[A, B]anarrayofprefixItems, andtuple[T, ...]one ofitems;dict[str, T]is anobjectofadditionalProperties;T | NoneandOptional[T]addnullto thetypeof a schema that has only a type, and are ananyOfwithnullotherwise, and other unions areanyOf;Literalis aconstor anenum, and so is anenum.Enumof its values, with theirtypewhere they have one;a
TypedDictis anobjectwhoserequiredare its required keys, closed withclosed=Trueof PEP 728, and a dataclass one whoserequiredare the fields without a default;datetime.datetime,datetime.date,datetime.time,uuid.UUIDandPyjo.URLare astringwith theformatdate-time,date,time,uuidanduri;Annotated[T, ...]adds a string as thedescription, and the keywords of adict, asminimumandpattern, or of a schema, asz.email(), without a class of a library of validation;a
typealias is its value, and aNewTypeits 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,enumandconst;minimum,maximum,exclusiveMinimum,exclusiveMaximumandmultipleOfof numbers;minLength,maxLength,patternandformatof strings;items,prefixItems,minItems,maxItems,uniqueItems,contains,minContainsandmaxContainsof arrays;properties,required,additionalProperties,patternProperties,propertyNames,minProperties,maxProperties,dependentRequiredanddependentSchemasof objects;allOf,anyOf,oneOf,not,if,thenandelse;$refto the schemas of the document, by a JSON Pointer, as to$defs, by their$anchorand by the$idof a schema in the schema, also to itself, and to the schemas of the registry ofadd_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
$schemanames 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)
- __json__() dict[str, str][source]¶
data = error.__json__()
The error as
Pyjo.JSONencodes it, withpath,keyword_pathandmessage.
- keyword_path¶
keyword_path = error.keyword_path
The JSON Pointer of the keyword in the schema, through the
$refthat 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.Pointertakes it, or of the missing property ofrequired.
- class Pyjo.JSON.Schema.Pyjo_JSON_Schema(data: dict[str, Any] | bool | None = None)[source]¶
Pyjo.JSON.Schemainherits all methods fromPyjo.Baseand 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.Schemaobject, of a schema written by hand, which can hold other objects ofPyjo.JSON.Schema, or of any value without arguments.
- 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
$idor the URI, where a$refof the schema finds it, and its$idand$anchortoo.
- 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
- property data: dict[str, Any] | bool[source]¶
data = schema.data
The schema as a
dict, with$defsfor the types that are used more than once or refer to themselves, orTrueorFalsefor a schema of any value or of none.# {'type': 'array', 'items': {'type': 'integer'}} Pyjo.JSON.Schema.of(list[int]).data
- datetime() Self[source]¶
schema = schema.datetime()
A string of the format
date-time, asz.iso.datetime(). zod also gives thepatternof 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 thepatternof 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, asenum, with theirtypewhere 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.
- 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
minimumandmaximum, 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()anddefault()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,dateandtime, asdatetime(),date()andtime()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, asdatahas them without them.
- classmethod lazy(getter: Callable[[], Any]) Self[source]¶
schema = z.lazy(lambda: category)
The schema that a function gives when
datais 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, asenum, with theirtypewhere 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()andloose().
- lt(value: float) Self[source]¶
schema = schema.lt(10)
A number less than the value,
exclusiveMaximum.
- 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,maximumandmaxItems.
- 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,minimumandminItems.
- 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, orSchemaand a number without a name.
- nonempty() Self[source]¶
schema = schema.nonempty()
A string or an array that is not empty,
min()of 1.
- nullable() Self[source]¶
schema = schema.nullable()
The schema of the value or of
null, in itstypewhere the schema has only a type, and inanyOfotherwise.# {'type': ['string', 'null']} z.string().nullable().data
- nullish() Self[source]¶
schema = schema.nullish()
nullable()andoptional().
- 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()anddefault()make them. A name that is a keyword of Python, or not a name of Python, goes in thedict. zod also givesadditionalProperties: falsefor 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
inputSchemaof a tool, anobjectwhosepropertiesare the parameters, with the ones without a defaultrequired, and the first paragraph of its docstring as itsdescription. The description of a parameter is the one of the field:param x:of its docstring, in reStructuredText, or of the sectionArgs:of the Google Python Style Guide.skipleaves out the first parameters, as the context or the controller that a tool or an action gets before its arguments;selfof a bound method is already gone.**kwargs: Tgives theadditionalPropertiesof the schema ofT, and without it the object has no other properties. A parameter without an annotation is of any value.*argsand 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 aPyjo.Exceptionwith the errors, one in each line.
- 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
outputSchemaof a tool, with the description of the field:returns:of its docstring, or of its sectionReturns:, orNonefor 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()andstrict().
- 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, asz.iso.time(). zod gives only thepatternof 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
restafter them, if any. zod also givesitems: falseto a tuple withoutrest, whichmaxItemsalready 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.
- uuid() S[source]¶
schema = z.uuid() schema = z.string().uuid()
A string of the format
uuid. zod also gives thepatternof 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.JSONdecodes it, and return aResult, which is true if the value is valid, with theErrorobjects of the value otherwise.formatis an annotation, as JSON Schema has it by default, and an assertion withformats.# "/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 ofPyjo.Testare.result = schema.validate(value) if not result: for error in result.errors: print(error.path, error.message)
- __json__() dict[str, Any][source]¶
data = result.__json__()
The result as
Pyjo.JSONencodes it,validand theerrors.
- __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
Errorobjects of the value, in aPyjo.Collection, empty if the value is valid.
- 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
inputSchemaof a tool, anobjectwhosepropertiesare the parameters, with the ones without a defaultrequired, and the first paragraph of its docstring as itsdescription. The description of a parameter is the one of the field:param x:of its docstring, in reStructuredText, or of the sectionArgs:of the Google Python Style Guide.skipleaves out the first parameters, as the context or the controller that a tool or an action gets before its arguments;selfof a bound method is already gone.**kwargs: Tgives theadditionalPropertiesof the schema ofT, and without it the object has no other properties. A parameter without an annotation is of any value.*argsand 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
outputSchemaof a tool, with the description of the field:returns:of its docstring, or of its sectionReturns:, orNonefor 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