API Reference#

Submodules#

jsonschema#

An implementation of JSON Schema for Python

The main functionality is provided by the validator classes for each of the supported JSON Schema versions.

Most commonly, jsonschema.validators.validate is the quickest way to simply validate a given instance under a schema, and will create a validator for you.

class jsonschema.ErrorTree(errors=())[source]#

ErrorTrees make it easier to check which validations failed.

property total_errors#

The total number of errors in the entire tree, including children.

class jsonschema.FormatChecker(formats: Iterable[str] | None = None)[source]#

A format property checker.

JSON Schema does not mandate that the format property actually do any validation. If validation is desired however, instances of this class can be hooked into validators to enable format validation.

FormatChecker objects always return True when asked about formats that they do not know how to validate.

To add a check for a custom format use the FormatChecker.checks decorator.

Parameters:

formats – The known formats to validate. This argument can be used to limit which formats will be used during validation.

check(instance: object, format: str) None[source]#

Check whether the instance conforms to the given format.

Parameters:
  • instance (any primitive type, i.e. str, number, bool) – The instance to check

  • format – The format that instance should conform to

Raises:

FormatError – if the instance does not conform to format

checks(format: str, raises: Union[Type[Exception], Tuple[Type[Exception], ...]] = ()) Callable[[_F], _F][source]#

Register a decorated function as validating a new format.

Parameters:
  • format – The format that the decorated function will check.

  • raises

    The exception(s) raised by the decorated function when an invalid instance is found.

    The exception object will be accessible as the jsonschema.exceptions.ValidationError.cause attribute of the resulting validation error.

conforms(instance: object, format: str) bool[source]#

Check whether the instance conforms to the given format.

Parameters:
  • instance (any primitive type, i.e. str, number, bool) – The instance to check

  • format – The format that instance should conform to

Returns:

whether it conformed

Return type:

bool

exception jsonschema.FormatError(message, cause=None)[source]#

Validating a format failed.

exception jsonschema.RefResolutionError(cause)[source]#

A ref could not be resolved.

class jsonschema.RefResolver(base_uri, referrer, store=pmap({}), cache_remote=True, handlers=(), urljoin_cache=None, remote_cache=None)[source]#

Resolve JSON References.

Parameters:
  • base_uri (str) – The URI of the referring document

  • referrer – The actual referring document

  • store (dict) – A mapping from URIs to documents to cache

  • cache_remote (bool) – Whether remote refs should be cached after first resolution

  • handlers (dict) – A mapping from URI schemes to functions that should be used to retrieve them

  • urljoin_cache (functools.lru_cache()) – A cache that will be used for caching the results of joining the resolution scope to subscopes.

  • remote_cache (functools.lru_cache()) – A cache that will be used for caching the results of resolved remote URLs.

cache_remote#

Whether remote refs should be cached after first resolution

Type:

bool

property base_uri#

Retrieve the current base URI, not including any fragment.

classmethod from_schema(schema, id_of=<function _id_of>, *args, **kwargs)[source]#

Construct a resolver from a JSON schema object.

Parameters:

schema – the referring schema

Returns:

RefResolver

in_scope(scope)[source]#

Temporarily enter the given scope for the duration of the context.

Deprecated since version v4.0.0.

pop_scope()[source]#

Exit the most recent entered scope.

Treats further dereferences as being performed underneath the original scope.

Don’t call this method more times than push_scope has been called.

push_scope(scope)[source]#

Enter a given sub-scope.

Treats further dereferences as being performed underneath the given scope.

property resolution_scope#

Retrieve the current resolution scope.

resolve(ref)[source]#

Resolve the given reference.

resolve_fragment(document, fragment)[source]#

Resolve a fragment within the referenced document.

Parameters:
  • document – The referent document

  • fragment (str) – a URI fragment to resolve within it

resolve_from_url(url)[source]#

Resolve the given URL.

resolve_remote(uri)[source]#

Resolve a remote uri.

If called directly, does not check the store first, but after retrieving the document at the specified URI it will be saved in the store if cache_remote is True.

Note

If the requests library is present, jsonschema will use it to request the remote uri, so that the correct encoding is detected and used.

If it isn’t, or if the scheme of the uri is not http or https, UTF-8 is assumed.

Parameters:

uri (str) – The URI to resolve

Returns:

The retrieved document

resolving(ref)[source]#

Resolve the given ref and enter its resolution scope.

Exits the scope on exit of this context manager.

Parameters:

ref (str) – The reference to resolve

exception jsonschema.SchemaError(message, validator=<unset>, path=(), cause=None, context=(), validator_value=<unset>, instance=<unset>, schema=<unset>, schema_path=(), parent=None, type_checker=<unset>)[source]#

A schema was invalid under its corresponding metaschema.

class jsonschema.TypeChecker(type_checkers: Mapping[str, Callable[[TypeChecker, Any], bool]] = pmap({}))[source]#

A type property checker.

A TypeChecker performs type checking for a Validator, converting between the defined JSON Schema types and some associated Python types or objects.

Modifying the behavior just mentioned by redefining which Python objects are considered to be of which JSON Schema types can be done using TypeChecker.redefine or TypeChecker.redefine_many, and types can be removed via TypeChecker.remove. Each of these return a new TypeChecker.

Parameters:

type_checkers – The initial mapping of types to their checking functions.

is_type(instance, type: str) bool[source]#

Check if the instance is of the appropriate type.

Parameters:
  • instance – The instance to check

  • type – The name of the type that is expected.

Raises:

jsonschema.exceptions.UndefinedTypeCheck – if type is unknown to this object.

redefine(type: str, fn) TypeChecker[source]#

Produce a new checker with the given type redefined.

Parameters:
  • type – The name of the type to check.

  • fn (collections.abc.Callable) – A callable taking exactly two parameters - the type checker calling the function and the instance to check. The function should return true if instance is of this type and false otherwise.

redefine_many(definitions=()) TypeChecker[source]#

Produce a new checker with the given types redefined.

Parameters:

definitions (dict) – A dictionary mapping types to their checking functions.

remove(*types) TypeChecker[source]#

Produce a new checker with the given types forgotten.

Parameters:

types – the names of the types to remove.

Raises:

jsonschema.exceptions.UndefinedTypeCheck – if any given type is unknown to this object

exception jsonschema.ValidationError(message, validator=<unset>, path=(), cause=None, context=(), validator_value=<unset>, instance=<unset>, schema=<unset>, schema_path=(), parent=None, type_checker=<unset>)[source]#

An instance was invalid under a provided schema.

jsonschema.validate(instance, schema, cls=None, *args, **kwargs)[source]#

Validate an instance under the given schema.

>>> validate([2, 3, 4], {"maxItems": 2})
Traceback (most recent call last):
    ...
ValidationError: [2, 3, 4] is too long

validate() will first verify that the provided schema is itself valid, since not doing so can lead to less obvious error messages and fail in less obvious or consistent ways.

If you know you have a valid schema already, especially if you intend to validate multiple instances with the same schema, you likely would prefer using the jsonschema.protocols.Validator.validate method directly on a specific validator (e.g. Draft20212Validator.validate).

Parameters:
  • instance – The instance to validate

  • schema – The schema to validate with

  • cls (jsonschema.protocols.Validator) – The class that will be used to validate the instance.

If the cls argument is not provided, two things will happen in accordance with the specification. First, if the schema has a $schema keyword containing a known meta-schema [1] then the proper validator will be used. The specification recommends that all schemas contain $schema properties for this reason. If no $schema property is found, the default validator class is the latest released draft.

Any other provided positional and keyword arguments will be passed on when instantiating the cls.

Raises:

Footnotes

jsonschema._format._F#

A format checker callable.

alias of TypeVar(‘_F’, bound=Callable[[object], bool])