API Reference

statham.__main__.main(input_uri)[source]

Get a schema from a URI, and then return the generated python module.

Parameters

input_uri (str) – URI of the target schema. This must follow the conventions of a JSON Schema "$ref" attribute.

Return type

str

Returns

Python module contents for generated models, as a string.

Model Reference

Parser

Parsing tools to convert JSON Schema dictionaries to Element instances.

Some JSON Schema documents will be converted to an equivalent but structurally differing representation. In particular, those that combine composition keywords or use multiple types will be recomposed using "allOf" and "anyOf" respectively. See full docs for more details.

statham.schema.parser.parse(schema)[source]

Parse a JSON Schema document to Element format.

Assumes references are already resolved, and that any "object" schemas or sub-schemas contain either a "title" annotation or an "_x_autotitle" annotation. See json-ref-dict for reference resolution and annotation tools.

Return type

List[Element]

Returns

A list of schema elements, starting with the top level element, followed by each element in the top-level schema "definitions".

statham.schema.parser.parse_element(schema, state=None)[source]

Parse a single JSON Schema element to an Element object.

Called by parse() when parsing entire documents.

>>> parse_element({"type": "string", "minLength": 3})
String(minLength=3)
Raises

FeatureNotImplementedError if recursive cycles are detected.

Raises

statham.schema.exceptions.SchemaParseError if problems are found in the provided schema.

Return type

Element

Returns

A single Element object equivalent to the schema described by parse_element.schema.

Elements

Untyped Elements

The Model Definition Language consists of composable elements, corresponding to JSON Sub-Schemas.

class statham.schema.elements.Element(*, default=NotPassed, const=NotPassed, enum=NotPassed, items=NotPassed, additionalItems=True, minItems=NotPassed, maxItems=NotPassed, uniqueItems=False, contains=NotPassed, minimum=NotPassed, maximum=NotPassed, exclusiveMinimum=NotPassed, exclusiveMaximum=NotPassed, multipleOf=NotPassed, format=NotPassed, pattern=NotPassed, minLength=NotPassed, maxLength=NotPassed, required=NotPassed, properties=NotPassed, patternProperties=NotPassed, additionalProperties=True, minProperties=NotPassed, maxProperties=NotPassed, propertyNames=NotPassed, dependencies=NotPassed, description=NotPassed)[source]

An un-typed schema element.

Accepts JSON Schema keywords as arguments.

Parameters
  • default (Union[Any, NotPassed]) – The default value this element should return when not provided.

  • const (Union[Any, NotPassed]) – Restrict this element to a constant value.

  • enum (Union[List[Any], NotPassed]) – Restrict this element to an enumeration of provided values.

  • items (Union[Element, List[Element], NotPassed]) – The Element with which to validate list items. If items is a list of Element, then each Element validates the corresponding index of the value. Subsequent values are validated by additionalItems.

  • additionalItems (Union[Element, bool]) – The Element with which to validate additional items in a list, when items is a list and shorter than the passed list.

  • minItems (Union[int, NotPassed]) – The minimum number of items to allow in list values.

  • maxItems (Union[int, NotPassed]) – The maximum number of items to allow in list values.

  • uniqueItems (bool) – If True, validate that list values contain unique elements.

  • contains (Union[Element, NotPassed]) – Validate that list values contain at least one element matching this Element.

  • minimum (Union[int, float, NotPassed]) – Validate that numeric values are greater than or equal to this value.

  • maximum (Union[int, float, NotPassed]) – Validate that numeric values are less than or equal to this value.

  • exclusiveMinimum (Union[int, float, NotPassed]) – Validate that numeric values are strictly greater than this value.

  • exclusiveMaximum (Union[int, float, NotPassed]) – Validate that numeric values are strictly less than this value.

  • multipleOf (Union[int, float, NotPassed]) – Validate that numeric values are are multiple of this value.

  • format (Union[str, NotPassed]) – Validate that string values conform to the specified format. See format_checker() to learn about included formats and how to add your own.

  • pattern (Union[str, NotPassed]) – Validate that string values match this value as a regular expression.

  • minLength (Union[int, NotPassed]) – Validate that string values are at least as long as this value.

  • maxLength (Union[int, NotPassed]) – Validate that string values are at most as long as this value.

  • required (Union[List[str], NotPassed]) – Validate that dictionary values contain each of these keys.

  • properties (Union[Dict[str, _Property], NotPassed]) – Validate that dictionary values match these properties. See statham.schema.property.Property for more information.

  • patternProperties (Union[Dict[str, Element], NotPassed]) – Validate that keys of dictionaries matching these patterns conform to the provided Element. Keys may match on multiple patternProperties and properties at the same time.

  • additionalProperties (Union[Element, bool]) – Validate properties not matched by either properties or patternProperties against this element. If True, any value is allowed. If False, no additional properties are allowed.

  • minProperties (Union[int, NotPassed]) – Validate that dictionary values contain at least this many members.

  • maxProperties (Union[int, NotPassed]) – Validate that dictionary values contain at most this many members.

  • propertyNames (Union[Element, NotPassed]) – Validate that keys of dictionary values match are accepted by this Element. Any Element is allowed here, but it is not useful to use any other than statham.schema.elements.String.

  • dependencies (Union[Dict[str, Union[List[str], Element]], NotPassed]) – Define JSON Schema dependencies. There are two types of dependencies. If the dict value is a list, then the each property name in that list must be present when the property name of the key is present. If the value is an Element, then it’s validation applies whenever the property name of the key is present. See Object Dependencies for more detail.

  • description (Union[str, NotPassed]) – Description of the element.

__call__(value, property_=None)[source]

Validate and convert input data against this Element.

Dictionary (object) values which pass validation are returned as a subclass of dict allowing attribute access.

Parameters
  • value (Any) – The input data.

  • property_ – Optionally specify the outer property scope enclosing this Element. Used automatically by object validation to produce more useful error messages.

Return type

Union[~T, NotPassed]

Returns

The parsed value.

class statham.schema.elements.Nothing[source]

Element which matches nothing. Equivalent to False.

Typed Elements

Typed schemas are declared using the following subclasses of statham.schema.elements.Element:

class statham.schema.elements.Array(items, *, default=NotPassed, const=NotPassed, enum=NotPassed, additionalItems=True, minItems=NotPassed, maxItems=NotPassed, uniqueItems=False, contains=NotPassed, description=NotPassed)[source]

JSON Schema "array" element.

Parameters

items (Union[Element[~Item], List[Element]]) – As in statham.schema.elements.Element, but as a required positional argument.

class statham.schema.elements.Boolean(*, default=NotPassed, const=NotPassed, enum=NotPassed, description=NotPassed)[source]

JSON Schema "boolean" element.

class statham.schema.elements.Null(*, default=NotPassed, const=NotPassed, enum=NotPassed, description=NotPassed)[source]

JSON Schema "null" element.

class statham.schema.elements.Integer(*, default=NotPassed, const=NotPassed, enum=NotPassed, minimum=NotPassed, maximum=NotPassed, exclusiveMinimum=NotPassed, exclusiveMaximum=NotPassed, multipleOf=NotPassed, description=NotPassed)[source]

JSON Schema "integer" element.

Accepts only python int.

class statham.schema.elements.Number(*, default=NotPassed, const=NotPassed, enum=NotPassed, minimum=NotPassed, maximum=NotPassed, exclusiveMinimum=NotPassed, exclusiveMaximum=NotPassed, multipleOf=NotPassed, description=NotPassed)[source]

JSON Schema "number" element.

Accepts python int or float.

class statham.schema.elements.Object(value=NotPassed, _property=Property(Element()))[source]

Base model for JSON Schema "object" elements.

"object" schemas are defined by declaring subclasses of Object. Properties are declared as class attributes, and other keywords are set as class arguments.

For example:

from statham.schema.elements import Object, String
from statham.schema.property import Property

class Poll(Object, additionalProperties=False):

    questions: List[str] = Property(String(), required=True)

poll = Poll({"questions": ["What's up?"]})
static inline(name, *, properties=None, **kwargs)[source]

Inline constructor for object schema elements.

Useful for minor objects, at the cost of reduced type checking support.

Parameters
  • name (str) – The name of the schema element.

  • properties (Optional[Dict[str, Any]]) – Dictionary of properties accepted by the schema element.

  • kwargs – Any accepted class args to Object subclasses.

Return type

ObjectMeta

Returns

A new subclass of Object with the appropriate validation rules.

class statham.schema.elements.String(*, default=NotPassed, const=NotPassed, enum=NotPassed, format=NotPassed, pattern=NotPassed, minLength=NotPassed, maxLength=NotPassed, description=NotPassed)[source]

JSON Schema "string" element.

Composition Elements

Four composition elements are available. Each accepts the composed element(s) as positional arguments, and statham.schema.elements.Element.default as an optional keyword argument.

class statham.schema.elements.Not(element, *, default=NotPassed)[source]

JSON Schema "not" element.

Element fails to validate if enclosed schema validates.

Parameters
  • element (Element) – The enclosed Element.

  • default (Any) – Inherited from Element.

class statham.schema.elements.AnyOf(*elements, default=NotPassed)[source]

JSON Schema "anyOf" element.

Must match at least one of the provided schemas.

Parameters
  • elements (Element) – The composed Element objects.

  • default (Any) – Inherited from Element.

class statham.schema.elements.OneOf(*elements, default=NotPassed)[source]

JSON Schema "oneOf" element.

Must match exactly one of the provided schemas.

Parameters
  • elements (Element) – The composed Element objects.

  • default (Any) – Inherited from Element.

class statham.schema.elements.AllOf(*elements, default=NotPassed)[source]

JSON Schema "allOf" element.

Must match all provided schemas.

Parameters
  • elements (Element) – The composed Element objects.

  • default (Any) – Inherited from Element.

Property

Required object properties are expressed inline. For example:

{
    "type": "object",
    "title": "MyObject",
    "required": ["value"],
    "properties": {"value": {"type": "string"}}
}

is expressed as

from statham.schema.elements import Object, String
from statham.schema.property import Property

class MyObject(Object):
    value = Property(String(), required=False)
class statham.schema.property.Property(element, *, required=False, source=None)[source]

Descriptor for adding a property when declaring an object schema model.

Return value is typed to inform instance-level interface (see type stubs).

Parameters
  • element (Element) – The JSON Schema Element object accepted by this property.

  • required (bool) – Whether this property is required. If false, then this field may be omitted when data is passed to the outer object’s constructor.

  • source (str) – The source name of this property. Only necessary if it must differ from that of the attribute.

Returns

The property descriptor for this element.

To hand property name conflicts, use the Property.source option. For example, to express a property called class, one could do the following:

class MyObject(Object):
    # Property called class
    class_: str = Property(String(), source="class")

Validation

This module contains implementation of JSON Schema validation keywords.

Each keyword is implemented as a subclass of Validator, and is instantiated with the relevant keywords. Validator instances may then be called to validate values.

Element automatically detects and instantiates its relevant validators, but validators may be used directly:

from statham.schema.validation import Minimum

validator = Minimum(minimum=3)
validator(5, None)  # OK
validator(2, None)  # ValidationError
statham.schema.validation.get_validators(element)[source]

Iterate all applicable validators for an Element.

Validators identify whether they are applicable for an element via the from_element class method. In general, this checks whether its parameters are present on the element with correct values.

Return type

Iterator[Validator]

class statham.schema.validation.base.Validator(*args)[source]

Base validator type.

Logic for given validation keywords is implemented in subclasses by overriding class variables and implementing the _validate() method.

types: ClassVar[Optional[Tuple[Type, ...]]] = None

Types on which this validator applies.

If None, apply to all values.

message: ClassVar[str] = ''

The error message to display on validation failure.

Can be tamplated on Validator.keywords.

keywords: Tuple[str, ...] = ()

Keywords which configure this validator.

These are used to configure the validator based on the statham.schema.elements.Element.

classmethod from_element(element)[source]

Construct validator from an Element instance.

Check for attributes matching keywords for this validator. If none are present, then return None.

Return type

Optional[Validator]

error_message()[source]

Generate the error message on failed validation.

__call__(value, property_)[source]

Apply the validator to a value.

Checks that value has correct type for this validator, runs validation logic and constructs the error message on failure.

Parameters
  • value (Any) – The value to validate.

  • property_ – The enclosing property if present - used for error reporting.

Raises

ValidationError if value fails validation.

class statham.schema.validation.base.InstanceOf(*args)[source]

Validate the type of a value.

class statham.schema.validation.base.NoMatch(*args)[source]

Don’t accept any passed value.

Used exclusively by Nothing.

class statham.schema.validation.base.Const(*args)[source]

Validate that passed values match a constant value.

class statham.schema.validation.base.Enum(*args)[source]

Validate that passed values are members of an enumeration.

class statham.schema.validation.array.MinItems(*args)[source]

Validate that arrays have a minimum number of items.

class statham.schema.validation.array.MaxItems(*args)[source]

Validate that arrays have a maximum number of items.

class statham.schema.validation.array.AdditionalItems(*args)[source]

Validate array items not covered by the "items" keyword.

Only relevant when using “tuple” style "items".

class statham.schema.validation.array.UniqueItems(*args)[source]

Validate that array items are unique.

class statham.schema.validation.array.Contains(*args)[source]

Validate that at least one array item matches a schema.

class statham.schema.validation.numeric.Minimum(*args)[source]

Validate that numeric values conform to a minimum.

class statham.schema.validation.numeric.Maximum(*args)[source]

Validate that numeric values conform to a maximum.

class statham.schema.validation.numeric.ExclusiveMinimum(*args)[source]

Validate that numeric values conform to an exclusive minimum.

class statham.schema.validation.numeric.ExclusiveMaximum(*args)[source]

Validate that numeric values conform to an exclusive maximum.

class statham.schema.validation.numeric.MultipleOf(*args)[source]

Validate that numeric values are a multiple of a given number.

class statham.schema.validation.object.Required(*args)[source]

Validate that object values contain all required properties.

classmethod from_element(element)[source]

Construct validator from an Element instance.

Check for attributes matching keywords for this validator. If none are present, then return None.

class statham.schema.validation.object.AdditionalProperties(*args)[source]

Validate that prohibited properties are not included.

class statham.schema.validation.object.MinProperties(*args)[source]

Validate that object values contain a minimum number of properties.

class statham.schema.validation.object.MaxProperties(*args)[source]

Validate that object values contain a maximum number of properties.

class statham.schema.validation.object.PropertyNames(*args)[source]

Validate that property names conform to a schema.

class statham.schema.validation.object.Dependencies(*args)[source]
class statham.schema.validation.string.Pattern(*args)[source]

Validate that string values match a regular expression.

class statham.schema.validation.string.MinLength(*args)[source]

Validate that string values are over a minimum length.

class statham.schema.validation.string.MaxLength(*args)[source]

Validate that string values are under a maximum length.

class statham.schema.validation.string.Format(*args)[source]

Validate that string values match a named format.

Additional formats may be registered via format_checker().

statham.schema.validation.format.format_checker: statham.schema.validation.format._FormatString = <statham.schema.validation.format._FormatString object>

Extensible implementation of the "format" keyword.

Validators for new formats may be registered as follows:

@format_checker.register("my_format")
def _validate_my_format(value: str) -> bool:
    # Return True if `value` matches `my_format`.
    ...

Serializers

Serializers for in-memory Element trees.

Elements may be serialized to a JSON dictionary or a Python module.

Python

statham.serializers.python.serialize_python(*elements)[source]

Serialize schema elements to python declaration string.

Captures declaration of the first Object elements, and any subsequent elements this depends on. Module imports and declaration order are dynamically inferred.

Parameters

elements (Element) – The Element objects to serialize.

Return type

str

Returns

Python module contents as a string, declaring the element tree.

JSON

statham.serializers.json.serialize_json(*elements, definitions=None)[source]

Serialize elements to a JSON Schema dictionary.

Object classes are included in definitions. The first element is the top-level schema.

Parameters
  • elements (Element) – The Element objects to serialize.

  • definitions (Optional[Dict[str, Element]]) – A dictionary of elements which should be members of the schema definitions keyword, and referenced everywhere else.

Return type

Dict[str, Any]

Returns

A JSON-serializable dictionary containing the JSON Schema for the provided element(s).

Exceptions

exception statham.schema.exceptions.StathamError[source]

Base exception for errors relating to statham.

exception statham.schema.exceptions.SchemaDefinitionError[source]

Raised when invalid schemas are declared in model definitions.

classmethod reserved_attribute(attribute_name)[source]
Return type

SchemaDefinitionError

exception statham.schema.exceptions.ValidationError[source]

Raised when JSON Schema validation fails for input data.

classmethod from_validator(property_, value, message)[source]
Return type

ValidationError

classmethod combine(property_, value, exceptions, message)[source]
Return type

ValidationError

classmethod multiple_composition_match(matching_models, data)[source]
exception statham.schema.exceptions.SchemaParseError[source]

Raised when parsing JSON Schema documents to statham models.

classmethod missing_title(schema)[source]
Return type

SchemaParseError

classmethod unresolvable_declaration()[source]
Return type

SchemaParseError

classmethod invalid_type(value)[source]
exception statham.schema.exceptions.FeatureNotImplementedError[source]

Raised when parsing valid JSON Schema features currently unsupported by statham.

classmethod unsupported_keywords(keywords)[source]
Return type

FeatureNotImplementedError