API Reference¶
-
statham.__main__.main(input_uri)¶ 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.
DSL Reference¶
Parser¶
Parsing tools to convert JSON Schema dictionaries to DSL 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 statham.dsl.elements.composition for more
details.
-
statham.dsl.parser.parse(schema)¶ Parse a JSON Schema document to DSL 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 DSL elements, starting with the top level element, followed by each element in the top-level schema
"definitions".
-
statham.dsl.parser.parse_element(schema, state=None)¶ Parse a single JSON Schema element to a DSL Element object.
Called by
parse()when parsing entire documents.>>> parse_element({"type": "string", "minLength": 3}) String(minLength=3)
- Raises
FeatureNotImplementedErrorif recursive cycles are detected.- Raises
statham.dsl.exceptions.SchemaParseErrorif problems are found in the provided schema.- Return type
Element- Returns
A single
Elementobject equivalent to the schema described byparse_element.schema.
Elements¶
Untyped Elements¶
The DSL consists of composable elements, corresponding to JSON Sub-Schemas.
-
class
statham.dsl.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)¶ 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]) – TheElementwith which to validate list items. Ifitemsis a list ofElement, then eachElementvalidates the corresponding index of the value. Subsequent values are validated byadditionalItems.additionalItems¶ (
Union[Element,bool]) – TheElementwith which to validate additional items in a list, whenitemsis 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) – IfTrue, validate that list values contain unique elements.contains¶ (
Union[Element,NotPassed]) – Validate that list values contain at least one element matching thisElement.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. Seeformat_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. Seestatham.dsl.property.Propertyfor more information.patternProperties¶ (
Union[Dict[str,Element],NotPassed]) – Validate that keys of dictionaries matching these patterns conform to the providedElement. Keys may match on multiplepatternPropertiesandpropertiesat the same time.additionalProperties¶ (
Union[Element,bool]) – Validate properties not matched by eitherpropertiesorpatternPropertiesagainst this element. IfTrue, any value is allowed. IfFalse, 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 thisElement. AnyElementis allowed here, but it is not useful to use any other thanstatham.dsl.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 anElement, then it’s validation applies whenever the property name of the key is present. See Object Dependencies for more detail.
-
class
statham.dsl.elements.Nothing¶ Element which matches nothing. Equivalent to
False.
Typed Elements¶
Typed schemas are declared using the following subclasses of statham.dsl.elements.Element:
-
class
statham.dsl.elements.Array(items, *, default=NotPassed, const=NotPassed, enum=NotPassed, additionalItems=True, minItems=NotPassed, maxItems=NotPassed, uniqueItems=False, contains=NotPassed)¶ JSON Schema
"array"element.- Parameters
items¶ (
Union[Element[~Item],List[Element]]) – As instatham.dsl.elements.Element, but as a required positional argument.
-
class
statham.dsl.elements.Boolean(*, default=NotPassed, const=NotPassed, enum=NotPassed)¶ JSON Schema
"boolean"element.
-
class
statham.dsl.elements.Null(*, default=NotPassed, const=NotPassed, enum=NotPassed)¶ JSON Schema
"null"element.
-
class
statham.dsl.elements.Integer(*, default=NotPassed, const=NotPassed, enum=NotPassed, minimum=NotPassed, maximum=NotPassed, exclusiveMinimum=NotPassed, exclusiveMaximum=NotPassed, multipleOf=NotPassed)¶ JSON Schema
"integer"element.Accepts only python int.
-
class
statham.dsl.elements.Number(*, default=NotPassed, const=NotPassed, enum=NotPassed, minimum=NotPassed, maximum=NotPassed, exclusiveMinimum=NotPassed, exclusiveMaximum=NotPassed, multipleOf=NotPassed)¶ JSON Schema
"number"element.Accepts python
intorfloat.
-
class
statham.dsl.elements.Object(value=NotPassed, _property=Property(Element()))¶ Base model for JSON Schema
"object"elements."object"schemas are defined by declaring subclasses ofObject. Properties are declared as class attributes, and other keywords are set as class arguments.For example:
from statham.dsl.elements import Object, String from statham.dsl.property import Property class Poll(Object, additionalProperties=False): questions: List[str] = Property(String(), required=True) poll = Poll({"questions": ["What's up?"]})
-
class
statham.dsl.elements.String(*, default=NotPassed, const=NotPassed, enum=NotPassed, format=NotPassed, pattern=NotPassed, minLength=NotPassed, maxLength=NotPassed)¶ JSON Schema
"string"element.
Composition Elements¶
Four composition elements are available. Each accepts the composed element(s) as positional arguments, and statham.dsl.elements.Element.default as an optional keyword argument.
-
class
statham.dsl.elements.Not(element, *, default=NotPassed)¶ JSON Schema
"not"element.Element fails to validate if enclosed schema validates.
-
class
statham.dsl.elements.AnyOf(*elements, default=NotPassed)¶ JSON Schema
"anyOf"element.Must match at least one of the provided schemas.
-
class
statham.dsl.elements.OneOf(*elements, default=NotPassed)¶ JSON Schema
"oneOf"element.Must match exactly one of the provided schemas.
Property¶
Required object properties are expressed inline. For example:
{
"type": "object",
"title": "MyObject",
"required": ["value"],
"properties": {"value": {"type": "string"}}
}
is expressed as
from statham.dsl.elements import Object, String
from statham.dsl.property import Property
class MyObject(Object):
value = Property(String(), required=False)
-
class
statham.dsl.property.Property(element, *, required=False, source=None)¶ 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.
To hand property name conflicts, use the
Property.sourceoption. 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.dsl.validation import Minimum
validator = Minimum(minimum=3)
validator(5, None) # OK
validator(2, None) # ValidationError
-
statham.dsl.validation.get_validators(element)¶ Iterate all applicable validators for an DSL 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.dsl.validation.base.Validator(*args)¶ 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.dsl.elements.Element.
-
classmethod
from_element(element)¶ Construct validator from a DSL Element instance.
Check for attributes matching keywords for this validator. If none are present, then return None.
- Return type
Optional[Validator]
-
error_message()¶ Generate the error message on failed validation.
-
__call__(value, property_)¶ 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
- Raises
ValidationErrorifvaluefails validation.
-
-
class
statham.dsl.validation.base.InstanceOf(*args)¶ Validate the type of a value.
-
class
statham.dsl.validation.base.NoMatch(*args)¶ Don’t accept any passed value.
Used exclusively by
Nothing.
-
class
statham.dsl.validation.base.Const(*args)¶ Validate that passed values match a constant value.
-
class
statham.dsl.validation.base.Enum(*args)¶ Validate that passed values are members of an enumeration.
-
class
statham.dsl.validation.array.MinItems(*args)¶ Validate that arrays have a minimum number of items.
-
class
statham.dsl.validation.array.MaxItems(*args)¶ Validate that arrays have a maximum number of items.
-
class
statham.dsl.validation.array.AdditionalItems(*args)¶ Validate array items not covered by the
"items"keyword.Only relevant when using “tuple” style
"items".
-
class
statham.dsl.validation.array.UniqueItems(*args)¶ Validate that array items are unique.
-
class
statham.dsl.validation.array.Contains(*args)¶ Validate that at least one array item matches a schema.
-
class
statham.dsl.validation.numeric.Minimum(*args)¶ Validate that numeric values conform to a minimum.
-
class
statham.dsl.validation.numeric.Maximum(*args)¶ Validate that numeric values conform to a maximum.
-
class
statham.dsl.validation.numeric.ExclusiveMinimum(*args)¶ Validate that numeric values conform to an exclusive minimum.
-
class
statham.dsl.validation.numeric.ExclusiveMaximum(*args)¶ Validate that numeric values conform to an exclusive maximum.
-
class
statham.dsl.validation.numeric.MultipleOf(*args)¶ Validate that numeric values are a multiple of a given number.
-
class
statham.dsl.validation.object.Required(*args)¶ Validate that object values contain all required properties.
-
class
statham.dsl.validation.object.AdditionalProperties(*args)¶ Validate that prohibited properties are not included.
-
class
statham.dsl.validation.object.MinProperties(*args)¶ Validate that object values contain a minimum number of properties.
-
class
statham.dsl.validation.object.MaxProperties(*args)¶ Validate that object values contain a maximum number of properties.
-
class
statham.dsl.validation.object.PropertyNames(*args)¶ Validate that property names conform to a schema.
-
class
statham.dsl.validation.object.Dependencies(*args)¶
-
class
statham.dsl.validation.string.Pattern(*args)¶ Validate that string values match a regular expression.
-
class
statham.dsl.validation.string.MinLength(*args)¶ Validate that string values are over a minimum length.
-
class
statham.dsl.validation.string.MaxLength(*args)¶ Validate that string values are under a maximum length.
-
class
statham.dsl.validation.string.Format(*args)¶ Validate that string values match a named format.
Additional formats may be registered via
format_checker().
-
statham.dsl.validation.format.format_checker: statham.dsl.validation.format._FormatString = <statham.dsl.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 DSL Element trees.
DSL Elements may be serialized to a JSON dictionary or a Python module.
Python¶
-
statham.serializers.python.serialize_python(*elements)¶ Serialize DSL 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.
Exceptions¶
-
exception
statham.dsl.exceptions.StathamError¶ Base exception for errors relating to
statham.
-
exception
statham.dsl.exceptions.SchemaDefinitionError¶ Raised when invalid schemas are declared in the DSL.
-
classmethod
reserved_attribute(attribute_name)¶ - Return type
-
classmethod
-
exception
statham.dsl.exceptions.ValidationError¶ Raised when JSON Schema validation fails for input data.
-
classmethod
from_validator(property_, value, message)¶ - Return type
-
classmethod
combine(property_, value, exceptions, message)¶ - Return type
-
classmethod
multiple_composition_match(matching_models, data)¶
-
classmethod
-
exception
statham.dsl.exceptions.SchemaParseError¶ Raised when parsing JSON Schema documents to DSL objects.
-
classmethod
missing_title(schema)¶ - Return type
-
classmethod
unresolvable_declaration()¶ - Return type
-
classmethod
invalid_type(value)¶
-
classmethod