Schema validation just got Pythonic
===============================================================================
**schema** is a library for validating Python data structures, such as those
obtained from config-files, forms, external services or command-line
parsing, converted from JSON/YAML (or something else) to Python data-types.
.. image:: https://secure.travis-ci.org/keleshev/schema.svg?branch=master
:target: https://travis-ci.org/keleshev/schema
.. image:: https://img.shields.io/codecov/c/github/keleshev/schema.svg
:target: http://codecov.io/github/keleshev/schema
Example
----------------------------------------------------------------------------
Here is a quick example to get a feeling of **schema**, validating a list of
entries with personal information:
.. code:: python
from schema import Schema, And, Use, Optional, SchemaError
schema = Schema(
[
{
"name": And(str, len),
"age": And(Use(int), lambda n: 18 <= n <= 99),
Optional("gender"): And(
str,
Use(str.lower),
lambda s: s in ("squid", "kid"),
),
}
]
)
data = [
{"name": "Sue", "age": "28", "gender": "Squid"},
{"name": "Sam", "age": "42"},
{"name": "Sacha", "age": "20", "gender": "KID"},
]
validated = schema.validate(data)
assert validated == [
{"name": "Sue", "age": 28, "gender": "squid"},
{"name": "Sam", "age": 42},
{"name": "Sacha", "age": 20, "gender": "kid"},
]
If data is valid, ``Schema.validate`` will return the validated data
(optionally converted with `Use` calls, see below).
If data is invalid, ``Schema`` will raise ``SchemaError`` exception.
If you just want to check that the data is valid, ``schema.is_valid(data)`` will
return ``True`` or ``False``.
Installation
-------------------------------------------------------------------------------
Use `pip <http://pip-installer.org>`_ or easy_install::
pip install schema
Alternatively, you can just drop ``schema.py`` file into your project—it is
self-contained.
- **schema** is tested with Python 2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9 and PyPy.
- **schema** follows `semantic versioning <http://semver.org>`_.
How ``Schema`` validates data
-------------------------------------------------------------------------------
Types
~~~~~
If ``Schema(...)`` encounters a type (such as ``int``, ``str``, ``object``,
etc.), it will check if the corresponding piece of data is an instance of that type,
otherwise it will raise ``SchemaError``.
.. code:: python
>>> from schema import Schema
>>> Schema(int).validate(123)
123
>>> Schema(int).validate('123')
Traceback (most recent call last):
...
schema.SchemaUnexpectedTypeError: '123' should be instance of 'int'
>>> Schema(object).validate('hai')
'hai'
Callables
~~~~~~~~~
If ``Schema(...)`` encounters a callable (function, class, or object with
``__call__`` method) it will call it, and if its return value evaluates to
``True`` it will continue validating, else—it will raise ``SchemaError``.
.. code:: python
>>> import os
>>> Schema(os.path.exists).validate('./')
'./'
>>> Schema(os.path.exists).validate('./non-existent/')
Traceback (most recent call last):
...
schema.SchemaError: exists('./non-existent/') should evaluate to True
>>> Schema(lambda n: n > 0).validate(123)
123
>>> Schema(lambda n: n > 0).validate(-12)
Traceback (most recent call last):
...
schema.SchemaError: <lambda>(-12) should evaluate to True
"Validatables"
~~~~~~~~~~~~~~
If ``Schema(...)`` encounters an object with method ``validate`` it will run
this method on corresponding data as ``data = obj.validate(data)``. This method
may raise ``SchemaError`` exception, which will tell ``Schema`` that that piece
of data is invalid, otherwise—it will continue validating.
An example of "validatable" is ``Regex``, that tries to match a string or a
buffer with the given regular expression (itself as a string, buffer or
compiled regex ``SRE_Pattern``):
.. code:: python
>>> from schema import Regex
>>> import re
>>> Regex(r'^foo').validate('foobar')
'foobar'
>>> Regex(r'^[A-Z]+$', flags=re.I).validate('those-dashes-dont-match')
Traceback (most recent call last):
...
schema.SchemaError: Regex('^[A-Z]+$', flags=re.IGNORECASE) does not match 'those-dashes-dont-match'
For a more general case, you can use ``Use`` for creating such objects.
``Use`` helps to use a function or type to convert a value while validating it:
.. code:: python
>>> from schema import Use
>>> Schema(Use(int)).validate('123')
123
>>> Schema(Use(lambda f: open(f, 'a'))).validate('LICENSE-MIT')
<_io.TextIOWrapper name='LICENSE-MIT' mode='a' encoding='UTF-8'>
Dropping the details, ``Use`` is basically:
.. code:: python
class Use(object):
def __init__(self, callable_):
self._callable = callable_
def validate(self, data):
try:
return self._callable(data)
except Exception as e:
raise SchemaError('%r raised %r' % (self._callable.__name__, e))
Sometimes you need to transform and validate part of data, but keep original data unchanged.
``Const`` helps to keep your data safe:
.. code:: python
>> from schema import Use, Const, And, Schema
>> from datetime import datetime
>> is_future = lambda date: datetime.now() > date
>> to_json = lambda v: {"timestamp": v}
>> Schema(And(Const(And(Use(datetime.fromtimestamp), is_future)), Use(to_json))).validate(1234567890)
{"timestamp": 1234567890}
Now you can write your own validation-aware classes and data types.
Lists, similar containers
~~~~~~~~~~~~~~~~~~~~~~~~~
If ``Schema(...)`` encounters an instance of ``list``, ``tuple``, ``set``
or ``frozenset``, it will validate contents of corresponding data container
against all schemas listed inside that container and aggregate all errors:
.. code:: python
>>> Schema([1, 0]).validate([1, 1, 0, 1])
[1, 1, 0, 1]
>>> Schema((int, float)).validate((5, 7, 8, 'not int or float here'))
Traceback (most recent call last):
...
schema.SchemaError: Or(<class 'int'>, <class 'float'>) did not validate 'not int or float here'
'not int or float here' should be instance of 'int'
'not int or float here' should be instance of 'float'
Dictionaries
~~~~~~~~~~~~
If ``Schema(...)`` encounters an instance of ``dict``, it will validate data
key-value pairs:
.. code:: python
>>> d = Schema(
... {"name": str, "age": lambda n: 18 <= n <= 99}
... ).validate(
... {"name": "Sue", "age": 28}
... )
>>> assert d == {'name': 'Sue', 'age': 28}
You can specify keys as schemas too:
.. code:: python
>>> schema = Schema({
... str: int, # string keys should have integer values
... int: None, # int keys should be always None
... })
>>> data = schema.validate({
... "key1": 1,
... "key2": 2,
... 10: None,
... 20: None,
... })
>>> schema.validate({
... "key1": 1,
... 10: "not None here",
... })
Traceback (most recent call last):
...
schema.SchemaError: Key '10' error:
None does not match 'not None here'
This is useful if you want to check certain key-values, but don't care
about others:
.. code:: python
>>> schema = Schema({
... "<id>": int,
... "<file>": Use(open),
... str: object, # don't care about other str keys
... })
>>> data = schema.validate({
... "<id>": 10,
... "<file>": "README.rst",
... "--verbose": True,
... })
You can mark a key as optional as follows:
.. code:: python
>>> Schema({
... "name": str,
... Optional("occupation"): str,
... }).validate({"name": "Sam"})
{'name': 'Sam'}
``Optional`` keys can also carry a ``default``, to be used when no key in the
data matches:
.. code:: python
>>> Schema({
... Optional("color", default="blue"): str,
... str: str,
... }).validate({"texture": "furry"}) == {
... "color": "blue",
... "texture": "furry",
... }
True
Defaults are used verbatim, not passed through any validators specified in the
value.
default can also be a callable:
.. code:: python
>>> from schema import Schema, Optional
>>> Schema({Optional('data', default=dict): {}}).validate({}) == {'data': {}}
True
Also, a caveat: If you specify types, **schema** won't validate the empty dict:
.. code:: python
>>> Schema({int:int}).is_valid({})
False
To do that, you need ``Schema(Or({int:int}, {}))``. This is unlike what happens with
lists, where ``Schema([int]).is_valid([])`` will return True.
**schema** has classes ``And`` and ``Or`` that help validating several schemas
for the same data:
.. code:: python
>>> from schema import And, Or
>>> Schema({'age': And(int, lambda n: 0 < n < 99)}).validate({'age': 7})
{'age': 7}
>>> Schema({'password': And(str, lambda s: len(s) > 6)}).validate({'password': 'hai'})
Traceback (most recent call last):
...
schema.SchemaError: Key 'password' error:
<lambda>('hai') should evaluate to True
>>> Schema(And(Or(int, float), lambda x: x > 0)).validate(3.1415)
3.1415
In a dictionary, you can also combine two keys in a "one or the other" manner. To do
so, use the `Or` class as a key:
.. code:: python
>>> from schema import Or, Schema
>>> schema = Schema({
... Or("key1", "key2", only_one=True): str
... })
>>> schema.validate({"key1": "test"}) # Ok
{'key1': 'test'}
>>> schema.validate({"key1": "test", "key2": "test"}) # SchemaError
Traceback (most recent call last):
...
schema.SchemaOnlyOneAllowedError: There are multiple keys present from the Or('key1', 'key2') condition
Hooks
~~~~~~~~~~
You can define hooks which are functions that are executed whenever a valid key:value is found.
The `Forbidden` class is an example of this.
You can mark a key as forbidden as follows:
.. code:: python
>>> from schema import Forbidden
>>> Schema({Forbidden('age'): object}).validate({'age': 50})
Traceback (most recent call last):
...
schema.SchemaForbiddenKeyError: Forbidden key encountered: 'age' in {'age': 50}
A few things are worth noting. First, the value paired with the forbidden
key determines whether it will be rejected:
.. code:: python
>>> Schema({Forbidden('age'): str, 'age': int}).validate({'age': 50})
{'age': 50}
Note: if we hadn't supplied the 'age' key here, the call would have failed too, but with
SchemaWrongKeyError, not SchemaForbiddenKeyError.
Second, Forbidden has a higher priority than standard keys, and consequently than Optional.
This means we can do that:
.. code:: python
>>> Schema({Forbidden('age'): object, Optional(str): object}).validate({'age': 50})
Traceback (most recent call last):
...
schema.SchemaForbiddenKeyError: Forbidden key encountered: 'age' in {'age': 50}
You can also define your own hooks. The following hook will call `_my_function` if `key` is encountered.
.. code:: python
from schema import Hook
def _my_function(key, scope, error):
print(key, scope, error)
Hook("key", handler=_my_function)
Here's an example where a `Deprecated` class is added to log warnings whenever a key is encountered:
.. code:: python
from schema import Hook, Schema
class Deprecated(Hook):
def __init__(self, *args, **kwargs):
kwargs["handler"] = lambda key, *args: logging.warn(f"`{key}` is deprecated. " + (self._error or ""))
super(Deprecated, self).__init__(*args, **kwargs)
Schema({Deprecated("test", "custom error message."): object}, ignore_extra_keys=True).validate({"test": "value"})
...
WARNING: `test` is deprecated. custom error message.
Extra Keys
~~~~~~~~~~
The ``Schema(...)`` parameter ``ignore_extra_keys`` causes validation to ignore extra keys in a dictionary, and also to not return them after validating.
.. code:: python
>>> schema = Schema({'name': str}, ignore_extra_keys=True)
>>> schema.validate({'name': 'Sam', 'age': '42'})
{'name': 'Sam'}
If you would like any extra keys returned, use ``object: object`` as one of the key/value pairs, which will match any key and any value.
Otherwise, extra keys will raise a ``SchemaError``.
Customized Validation
~~~~~~~~~~~~~~~~~~~~~~~
The ``Schema.validate`` method accepts additional keyword arguments. The
keyword arguments will be propagated to the ``validate`` method of any
child validatables (including any ad-hoc ``Schema`` objects), or the default
value callable (if a callable is specified) for ``Optional`` keys.
This feature can be used together with inheritance of the ``Schema`` class
for customized validation.
Here is an example where a "post-validation" hook that runs after validation
against a sub-schema in a larger schema:
.. code:: python
class EventSchema(schema.Schema):
def validate(self, data, _is_event_schema=True):
data = super(EventSchema, self).validate(data, _is_event_schema=False)
if _is_event_schema and data.get("minimum", None) is None:
data["minimum"] = data["capacity"]
return data
events_schema = schema.Schema(
{
str: EventSchema({
"capacity": int,
schema.Optional("minimum"): int, # default to capacity
})
}
)
data = {'event1': {'capacity': 1}, 'event2': {'capacity': 2, 'minimum': 3}}
events = events_schema.validate(data)
assert events['event1']['minimum'] == 1 # == capacity
assert events['event2']['minimum'] == 3
Note that the additional keyword argument ``_is_event_schema`` is necessary to
limit the customized behavior to the ``EventSchema`` object itself so that it
won't affect any recursive invoke of the ``self.__class__.validate`` for the
child schemas (e.g., the call to ``Schema("capacity").validate("capacity")``).
User-friendly error reporting
-------------------------------------------------------------------------------
You can pass a keyword argument ``error`` to any of validatable classes
(such as ``Schema``, ``And``, ``Or``, ``Regex``, ``Use``) to report this error
instead of a built-in one.
.. code:: python
>>> Schema(Use(int, error='Invalid year')).validate('XVII')
Traceback (most recent call last):
...
schema.SchemaError: Invalid year
You can see all errors that occurred by accessing exception's ``exc.autos``
for auto-generated error messages, and ``exc.errors`` for errors
which had ``error`` text passed to them.
You can exit with ``sys.exit(exc.code)`` if you want to show the messages
to the user without traceback. ``error`` messages are given precedence in that
case.
A JSON API example
-------------------------------------------------------------------------------
Here is a quick example: validation of
`create a gist <http://developer.github.com/v3/gists/>`_
request from github API.
.. code:: python
>>> gist = '''{"description": "the description for this gist",
... "public": true,
... "files": {
... "file1.txt": {"content": "String file contents"},
... "other.txt": {"content": "Another file contents"}}}'''
>>> from schema import Schema, And, Use, Optional
>>> import json
>>> gist_schema = Schema(
... And(
... Use(json.loads), # first convert from JSON
... # use str since json returns unicode
... {
... Optional("description"): str,
... "public": bool,
... "files": {str: {"content": str}},
... },
... )
... )
>>> gist = gist_schema.validate(gist)
# gist:
{u'description': u'the description for this gist',
u'files': {u'file1.txt': {u'content': u'String file contents'},
u'other.txt': {u'content': u'Another file contents'}},
u'public': True}
Using **schema** with `docopt <http://github.com/docopt/docopt>`_
-------------------------------------------------------------------------------
Assume you are using **docopt** with the following usage-pattern:
Usage: my_program.py [--count=N] <path> <files>...
and you would like to validate that ``<files>`` are readable, and that
``<path>`` exists, and that ``--count`` is either integer from 0 to 5, or
``None``.
Assuming **docopt** returns the following dict:
.. code:: python
>>> args = {
... "<files>": ["LICENSE-MIT", "setup.py"],
... "<path>": "../",
... "--count": "3",
... }
this is how you validate it using ``schema``:
.. code:: python
>>> from schema import Schema, And, Or, Use
>>> import os
>>> s = Schema({
... "<files>": [Use(open)],
... "<path>": os.path.exists,
... "--count": Or(None, And(Use(int), lambda n: 0 < n < 5)),
... })
>>> args = s.validate(args)
>>> args['<files>']
[<_io.TextIOWrapper name='LICENSE-MIT' ...>, <_io.TextIOWrapper name='setup.py' ...]
>>> args['<path>']
'../'
>>> args['--count']
3
As you can see, **schema** validated data successfully, opened files and
converted ``'3'`` to ``int``.
JSON schema
-----------
You can also generate standard `draft-07 JSON schema <https://json-schema.org/>`_ from a dict ``Schema``.
This can be used to add word completion, validation, and documentation directly in code editors.
The output schema can also be used with JSON schema compatible libraries.
JSON: Generating
~~~~~~~~~~~~~~~~
Just define your schema normally and call ``.json_schema()`` on it. The output is a Python dict, you need to dump it to JSON.
.. code:: python
>>> from schema import Optional, Schema
>>> import json
>>> s = Schema({
... "test": str,
... "nested": {Optional("other"): str},
... })
>>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json"))
# json_schema
{
"type":"object",
"properties": {
"test": {"type": "string"},
"nested": {
"type":"object",
"properties": {
"other": {"type": "string"}
},
"required": [],
"additionalProperties": false
}
},
"required":[
"test",
"nested"
],
"additionalProperties":false,
"$id":"https://example.com/my-schema.json",
"$schema":"http://json-schema.org/draft-07/schema#"
}
You can add descriptions for the schema elements using the ``Literal`` object instead of a string. The main schema can also have a description.
These will appear in IDEs to help your users write a configuration.
.. code:: python
>>> from schema import Literal, Schema
>>> import json
>>> s = Schema(
... {Literal("project_name", description="Names must be unique"): str},
... description="Project schema",
... )
>>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json"), indent=4)
# json_schema
{
"type": "object",
"properties": {
"project_name": {
"description": "Names must be unique",
"type": "string"
}
},
"required": [
"project_name"
],
"additionalProperties": false,
"$id": "https://example.com/my-schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Project schema"
}
JSON: Supported validations
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The resulting JSON schema is not guaranteed to accept the same objects as the library would accept, since some validations are not implemented or
have no JSON schema equivalent. This is the case of the ``Use`` and ``Hook`` objects for example.
Implemented
'''''''''''
`Object properties <https://json-schema.org/understanding-json-schema/reference/object.html#properties>`_
Use a dict literal. The dict keys are the JSON schema properties.
Example:
``Schema({"test": str})``
becomes
``{'type': 'object', 'properties': {'test': {'type': 'string'}}, 'required': ['test'], 'additionalProperties': False}``.
Please note that attributes are required by default. To create optional attributes use ``Optional``, like so:
``Schema({Optional("test"): str})``
becomes
``{'type': 'object', 'properties': {'test': {'type': 'string'}}, 'required': [], 'additionalProperties': False}``
additionalProperties is set to true when at least one of the conditions is met:
- ignore_extra_keys is True
- at least one key is `str` or `object`
For example:
``Schema({str: str})`` and ``Schema({}, ignore_extra_keys=True)``
both becomes
``{'type': 'object', 'properties' : {}, 'required': [], 'additionalProperties': True}``
and
``Schema({})``
becomes
``{'type': 'object', 'properties' : {}, 'required': [], 'additionalProperties': False}``
Types
Use the Python type name directly. It will be converted to the JSON name:
- ``str`` -> `string <https://json-schema.org/understanding-json-schema/reference/string.html>`_
- ``int`` -> `integer <https://json-schema.org/understanding-json-schema/reference/numeric.html#integer>`_
- ``float`` -> `number <https://json-schema.org/understanding-json-schema/reference/numeric.html#number>`_
- ``bool`` -> `boolean <https://json-schema.org/understanding-json-schema/reference/boolean.html>`_
- ``list`` -> `array <https://json-schema.org/understanding-json-schema/reference/array.html>`_
- ``dict`` -> `object <https://json-schema.org/understanding-json-schema/reference/object.html>`_
Example:
``Schema(float)``
becomes
``{"type": "number"}``
`Array items <https://json-schema.org/understanding-json-schema/reference/array.html#items>`_
Surround a schema with ``[]``.
Example:
``Schema([str])`` means an array of string and becomes:
``{'type': 'array', 'items': {'type': 'string'}}``
`Enumerated values <https://json-schema.org/understanding-json-schema/reference/generic.html#enumerated-values>`_
Use `Or`.
Example:
``Schema(Or(1, 2, 3))`` becomes
``{"enum": [1, 2, 3]}``
`Constant values <https://json-schema.org/understanding-json-schema/reference/generic.html#constant-values>`_
Use the value itself.
Example:
``Schema("name")`` becomes
``{"const": "name"}``
`Regular expressions <https://json-schema.org/understanding-json-schema/reference/regular_expressions.html>`_
Use ``Regex``.
Example:
``Schema(Regex("^v\d+"))`` becomes
``{'type': 'string', 'pattern': '^v\\d+'}``
`Annotations (title and description) <https://json-schema.org/understanding-json-schema/reference/generic.html#annotations>`_
You can use the ``name`` and ``description`` parameters of the ``Schema`` object init method.
To add description to keys, replace a str with a ``Literal`` object.
Example:
``Schema({Literal("test", description="A description"): str})``
is equivalent to
``Schema({"test": str})``
with the description added to the resulting JSON schema.
`Combining schemas with allOf <https://json-schema.org/understanding-json-schema/reference/combining.html#allof>`_
Use ``And``
Example:
``Schema(And(str, "value"))``
becomes
``{"allOf": [{"type": "string"}, {"const": "value"}]}``
Note that this example is not really useful in the real world, since ``const`` already implies the type.
`Combining schemas with anyOf <https://json-schema.org/understanding-json-schema/reference/combining.html#anyof>`_
Use ``Or``
Example:
``Schema(Or(str, int))``
becomes
``{"anyOf": [{"type": "string"}, {"type": "integer"}]}``
Not implemented
'''''''''''''''
The following JSON schema validations cannot be generated from this library.
- `String length <https://json-schema.org/understanding-json-schema/reference/string.html#length>`_
However, those can be implemented using ``Regex``
- `String format <https://json-schema.org/understanding-json-schema/reference/string.html#format>`_
However, those can be implemented using ``Regex``
- `Object dependencies <https://json-schema.org/understanding-json-schema/reference/object.html#dependencies>`_
- `Array length <https://json-schema.org/understanding-json-schema/reference/array.html#length>`_
- `Array uniqueness <https://json-schema.org/understanding-json-schema/reference/array.html#uniqueness>`_
- `Numeric multiples <https://json-schema.org/understanding-json-schema/reference/numeric.html#multiples>`_
- `Numeric ranges <https://json-schema.org/understanding-json-schema/reference/numeric.html#range>`_
- `Property Names <https://json-schema.org/understanding-json-schema/reference/object.html#property-names>`_
Not implemented. We suggest listing the possible keys instead. As a tip, you can use ``Or`` as a dict key.
Example:
``Schema({Or("name1", "name2"): str})``
- `Annotations (default and examples) <https://json-schema.org/understanding-json-schema/reference/generic.html#annotations>`_
- `Combining schemas with oneOf <https://json-schema.org/understanding-json-schema/reference/combining.html#oneof>`_
- `Not <https://json-schema.org/understanding-json-schema/reference/combining.html#not>`_
- `Object size <https://json-schema.org/understanding-json-schema/reference/object.html#size>`_
- `additionalProperties having a different schema (true and false is supported)`
JSON: Minimizing output size
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Explicit Reuse
''''''''''''''
If your JSON schema is big and has a lot of repetition, it can be made simpler and smaller by defining Schema objects as reference.
These references will be placed in a "definitions" section in the main schema.
`You can look at the JSON schema documentation for more information <https://json-schema.org/understanding-json-schema/structuring.html#reuse>`_
.. code:: python
>>> from schema import Optional, Schema
>>> import json
>>> s = Schema({
... "test": str,
... "nested": Schema({Optional("other"): str}, name="nested", as_reference=True)
... })
>>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json"), indent=4)
# json_schema
{
"type": "object",
"properties": {
"test": {
"type": "string"
},
"nested": {
"$ref": "#/definitions/nested"
}
},
"required": [
"test",
"nested"
],
"additionalProperties": false,
"$id": "https://example.com/my-schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"nested": {
"type": "object",
"properties": {
"other": {
"type": "string"
}
},
"required": [],
"additionalProperties": false
}
}
}
This becomes really useful when using the same object several times
.. code:: python
>>> from schema import Optional, Or, Schema
>>> import json
>>> language_configuration = Schema(
... {"autocomplete": bool, "stop_words": [str]},
... name="language",
... as_reference=True,
... )
>>> s = Schema({Or("ar", "cs", "de", "el", "eu", "en", "es", "fr"): language_configuration})
>>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json"), indent=4)
# json_schema
{
"type": "object",
"properties": {
"ar": {
"$ref": "#/definitions/language"
},
"cs": {
"$ref": "#/definitions/language"
},
"de": {
"$ref": "#/definitions/language"
},
"el": {
"$ref": "#/definitions/language"
},
"eu": {
"$ref": "#/definitions/language"
},
"en": {
"$ref": "#/definitions/language"
},
"es": {
"$ref": "#/definitions/language"
},
"fr": {
"$ref": "#/definitions/language"
}
},
"required": [],
"additionalProperties": false,
"$id": "https://example.com/my-schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"language": {
"type": "object",
"properties": {
"autocomplete": {
"type": "boolean"
},
"stop_words": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"autocomplete",
"stop_words"
],
"additionalProperties": false
}
}
}
Automatic reuse
'''''''''''''''
If you want to minimize the output size without using names explicitly, you can have the library generate hashes of parts of the output JSON
schema and use them as references throughout.
Enable this behaviour by providing the parameter ``use_refs`` to the json_schema method.
Be aware that this method is less often compatible with IDEs and JSON schema libraries.
It produces a JSON schema that is more difficult to read by humans.
.. code:: python
>>> from schema import Optional, Or, Schema
>>> import json
>>> language_configuration = Schema({"autocomplete": bool, "stop_words": [str]})
>>> s = Schema({Or("ar", "cs", "de", "el", "eu", "en", "es", "fr"): language_configuration})
>>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json", use_refs=True), indent=4)
# json_schema
{
"type": "object",
"properties": {
"ar": {
"type": "object",
"properties": {
"autocomplete": {
"type": "boolean",
"$id": "#6456104181059880193"
},
"stop_words": {
"type": "array",
"items": {
"type": "string",
"$id": "#1856069563381977338"
}
}
},
"required": [
"autocomplete",
"stop_words"
],
"additionalProperties": false
},
"cs": {
"type": "object",
"properties": {
"autocomplete": {
"$ref": "#6456104181059880193"
},
"stop_words": {
"type": "array",
"items": {
"$ref": "#1856069563381977338"
},
"$id": "#-5377945144312515805"
}
},
"required": [
"autocomplete",
"stop_words"
],
"additionalProperties": false
},
"de": {
"type": "object",
"properties": {
"autocomplete": {
"$ref": "#6456104181059880193"
},
"stop_words": {
"$ref": "#-5377945144312515805"
}
},
"required": [
"autocomplete",
"stop_words"
],
"additionalProperties": false,
"$id": "#-8142886105174600858"
},
"el": {
"$ref": "#-8142886105174600858"
},
"eu": {
"$ref": "#-8142886105174600858"
},
"en": {
"$ref": "#-8142886105174600858"
},
"es": {
"$ref": "#-8142886105174600858"
},
"fr": {
"$ref": "#-8142886105174600858"
}
},
"required": [],
"additionalProperties": false,
"$id": "https://example.com/my-schema.json",
"$schema": "http://json-schema.org/draft-07/schema#"
}
Raw data
{
"_id": null,
"home_page": "https://github.com/keleshev/schema",
"name": "schema",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "schema json validation",
"author": "Vladimir Keleshev",
"author_email": "vladimir@keleshev.com",
"download_url": "https://files.pythonhosted.org/packages/d4/01/0ea2e66bad2f13271e93b729c653747614784d3ebde219679e41ccdceecd/schema-0.7.7.tar.gz",
"platform": null,
"description": "Schema validation just got Pythonic \n===============================================================================\n\n**schema** is a library for validating Python data structures, such as those\nobtained from config-files, forms, external services or command-line\nparsing, converted from JSON/YAML (or something else) to Python data-types.\n\n\n.. image:: https://secure.travis-ci.org/keleshev/schema.svg?branch=master\n :target: https://travis-ci.org/keleshev/schema\n\n.. image:: https://img.shields.io/codecov/c/github/keleshev/schema.svg\n :target: http://codecov.io/github/keleshev/schema\n\nExample\n----------------------------------------------------------------------------\n\nHere is a quick example to get a feeling of **schema**, validating a list of\nentries with personal information:\n\n.. code:: python\n \n from schema import Schema, And, Use, Optional, SchemaError\n \n schema = Schema(\n [\n {\n \"name\": And(str, len),\n \"age\": And(Use(int), lambda n: 18 <= n <= 99),\n Optional(\"gender\"): And(\n str,\n Use(str.lower),\n lambda s: s in (\"squid\", \"kid\"),\n ),\n }\n ]\n )\n \n data = [\n {\"name\": \"Sue\", \"age\": \"28\", \"gender\": \"Squid\"},\n {\"name\": \"Sam\", \"age\": \"42\"},\n {\"name\": \"Sacha\", \"age\": \"20\", \"gender\": \"KID\"},\n ]\n \n validated = schema.validate(data)\n \n assert validated == [\n {\"name\": \"Sue\", \"age\": 28, \"gender\": \"squid\"},\n {\"name\": \"Sam\", \"age\": 42},\n {\"name\": \"Sacha\", \"age\": 20, \"gender\": \"kid\"},\n ]\n\n\n\nIf data is valid, ``Schema.validate`` will return the validated data\n(optionally converted with `Use` calls, see below).\n\nIf data is invalid, ``Schema`` will raise ``SchemaError`` exception.\nIf you just want to check that the data is valid, ``schema.is_valid(data)`` will\nreturn ``True`` or ``False``.\n\n\nInstallation\n-------------------------------------------------------------------------------\n\nUse `pip <http://pip-installer.org>`_ or easy_install::\n\n pip install schema\n\nAlternatively, you can just drop ``schema.py`` file into your project\u2014it is\nself-contained.\n\n- **schema** is tested with Python 2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9 and PyPy.\n- **schema** follows `semantic versioning <http://semver.org>`_.\n\nHow ``Schema`` validates data\n-------------------------------------------------------------------------------\n\nTypes\n~~~~~\n\nIf ``Schema(...)`` encounters a type (such as ``int``, ``str``, ``object``,\netc.), it will check if the corresponding piece of data is an instance of that type,\notherwise it will raise ``SchemaError``.\n\n.. code:: python\n\n >>> from schema import Schema\n\n >>> Schema(int).validate(123)\n 123\n\n >>> Schema(int).validate('123')\n Traceback (most recent call last):\n ...\n schema.SchemaUnexpectedTypeError: '123' should be instance of 'int'\n\n >>> Schema(object).validate('hai')\n 'hai'\n\nCallables\n~~~~~~~~~\n\nIf ``Schema(...)`` encounters a callable (function, class, or object with\n``__call__`` method) it will call it, and if its return value evaluates to\n``True`` it will continue validating, else\u2014it will raise ``SchemaError``.\n\n.. code:: python\n\n >>> import os\n\n >>> Schema(os.path.exists).validate('./')\n './'\n\n >>> Schema(os.path.exists).validate('./non-existent/')\n Traceback (most recent call last):\n ...\n schema.SchemaError: exists('./non-existent/') should evaluate to True\n\n >>> Schema(lambda n: n > 0).validate(123)\n 123\n\n >>> Schema(lambda n: n > 0).validate(-12)\n Traceback (most recent call last):\n ...\n schema.SchemaError: <lambda>(-12) should evaluate to True\n\n\"Validatables\"\n~~~~~~~~~~~~~~\n\nIf ``Schema(...)`` encounters an object with method ``validate`` it will run\nthis method on corresponding data as ``data = obj.validate(data)``. This method\nmay raise ``SchemaError`` exception, which will tell ``Schema`` that that piece\nof data is invalid, otherwise\u2014it will continue validating.\n\nAn example of \"validatable\" is ``Regex``, that tries to match a string or a\nbuffer with the given regular expression (itself as a string, buffer or\ncompiled regex ``SRE_Pattern``):\n\n.. code:: python\n\n >>> from schema import Regex\n >>> import re\n\n >>> Regex(r'^foo').validate('foobar')\n 'foobar'\n\n >>> Regex(r'^[A-Z]+$', flags=re.I).validate('those-dashes-dont-match')\n Traceback (most recent call last):\n ...\n schema.SchemaError: Regex('^[A-Z]+$', flags=re.IGNORECASE) does not match 'those-dashes-dont-match'\n\nFor a more general case, you can use ``Use`` for creating such objects.\n``Use`` helps to use a function or type to convert a value while validating it:\n\n.. code:: python\n\n >>> from schema import Use\n\n >>> Schema(Use(int)).validate('123')\n 123\n\n >>> Schema(Use(lambda f: open(f, 'a'))).validate('LICENSE-MIT')\n <_io.TextIOWrapper name='LICENSE-MIT' mode='a' encoding='UTF-8'>\n\nDropping the details, ``Use`` is basically:\n\n.. code:: python\n\n class Use(object):\n\n def __init__(self, callable_):\n self._callable = callable_\n\n def validate(self, data):\n try:\n return self._callable(data)\n except Exception as e:\n raise SchemaError('%r raised %r' % (self._callable.__name__, e))\n\n\nSometimes you need to transform and validate part of data, but keep original data unchanged.\n``Const`` helps to keep your data safe:\n\n.. code:: python\n\n >> from schema import Use, Const, And, Schema\n\n >> from datetime import datetime\n\n >> is_future = lambda date: datetime.now() > date\n\n >> to_json = lambda v: {\"timestamp\": v}\n\n >> Schema(And(Const(And(Use(datetime.fromtimestamp), is_future)), Use(to_json))).validate(1234567890)\n {\"timestamp\": 1234567890}\n\nNow you can write your own validation-aware classes and data types.\n\nLists, similar containers\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf ``Schema(...)`` encounters an instance of ``list``, ``tuple``, ``set``\nor ``frozenset``, it will validate contents of corresponding data container\nagainst all schemas listed inside that container and aggregate all errors:\n\n.. code:: python\n\n >>> Schema([1, 0]).validate([1, 1, 0, 1])\n [1, 1, 0, 1]\n\n >>> Schema((int, float)).validate((5, 7, 8, 'not int or float here'))\n Traceback (most recent call last):\n ...\n schema.SchemaError: Or(<class 'int'>, <class 'float'>) did not validate 'not int or float here'\n 'not int or float here' should be instance of 'int'\n 'not int or float here' should be instance of 'float'\n\nDictionaries\n~~~~~~~~~~~~\n\nIf ``Schema(...)`` encounters an instance of ``dict``, it will validate data\nkey-value pairs:\n\n.. code:: python\n\n >>> d = Schema(\n ... {\"name\": str, \"age\": lambda n: 18 <= n <= 99}\n ... ).validate(\n ... {\"name\": \"Sue\", \"age\": 28}\n ... )\n\n >>> assert d == {'name': 'Sue', 'age': 28}\n\nYou can specify keys as schemas too:\n\n.. code:: python\n\n >>> schema = Schema({\n ... str: int, # string keys should have integer values\n ... int: None, # int keys should be always None\n ... })\n\n >>> data = schema.validate({\n ... \"key1\": 1,\n ... \"key2\": 2,\n ... 10: None,\n ... 20: None,\n ... })\n\n >>> schema.validate({\n ... \"key1\": 1,\n ... 10: \"not None here\",\n ... })\n Traceback (most recent call last):\n ...\n schema.SchemaError: Key '10' error:\n None does not match 'not None here'\n\nThis is useful if you want to check certain key-values, but don't care\nabout others:\n\n.. code:: python\n\n >>> schema = Schema({\n ... \"<id>\": int,\n ... \"<file>\": Use(open),\n ... str: object, # don't care about other str keys\n ... })\n\n >>> data = schema.validate({\n ... \"<id>\": 10,\n ... \"<file>\": \"README.rst\",\n ... \"--verbose\": True,\n ... })\n\nYou can mark a key as optional as follows:\n\n.. code:: python\n\n >>> Schema({\n ... \"name\": str,\n ... Optional(\"occupation\"): str,\n ... }).validate({\"name\": \"Sam\"})\n {'name': 'Sam'}\n\n``Optional`` keys can also carry a ``default``, to be used when no key in the\ndata matches:\n\n.. code:: python\n\n >>> Schema({\n ... Optional(\"color\", default=\"blue\"): str,\n ... str: str,\n ... }).validate({\"texture\": \"furry\"}) == {\n ... \"color\": \"blue\",\n ... \"texture\": \"furry\",\n ... }\n True\n\nDefaults are used verbatim, not passed through any validators specified in the\nvalue.\n\ndefault can also be a callable:\n\n.. code:: python\n\n >>> from schema import Schema, Optional\n >>> Schema({Optional('data', default=dict): {}}).validate({}) == {'data': {}}\n True\n\nAlso, a caveat: If you specify types, **schema** won't validate the empty dict:\n\n.. code:: python\n\n >>> Schema({int:int}).is_valid({})\n False\n\nTo do that, you need ``Schema(Or({int:int}, {}))``. This is unlike what happens with\nlists, where ``Schema([int]).is_valid([])`` will return True.\n\n\n**schema** has classes ``And`` and ``Or`` that help validating several schemas\nfor the same data:\n\n.. code:: python\n\n >>> from schema import And, Or\n\n >>> Schema({'age': And(int, lambda n: 0 < n < 99)}).validate({'age': 7})\n {'age': 7}\n\n >>> Schema({'password': And(str, lambda s: len(s) > 6)}).validate({'password': 'hai'})\n Traceback (most recent call last):\n ...\n schema.SchemaError: Key 'password' error:\n <lambda>('hai') should evaluate to True\n\n >>> Schema(And(Or(int, float), lambda x: x > 0)).validate(3.1415)\n 3.1415\n\nIn a dictionary, you can also combine two keys in a \"one or the other\" manner. To do\nso, use the `Or` class as a key:\n\n.. code:: python\n\n >>> from schema import Or, Schema\n >>> schema = Schema({\n ... Or(\"key1\", \"key2\", only_one=True): str\n ... })\n\n >>> schema.validate({\"key1\": \"test\"}) # Ok\n {'key1': 'test'}\n\n >>> schema.validate({\"key1\": \"test\", \"key2\": \"test\"}) # SchemaError\n Traceback (most recent call last):\n ...\n schema.SchemaOnlyOneAllowedError: There are multiple keys present from the Or('key1', 'key2') condition\n\nHooks\n~~~~~~~~~~\nYou can define hooks which are functions that are executed whenever a valid key:value is found.\nThe `Forbidden` class is an example of this.\n\nYou can mark a key as forbidden as follows:\n\n.. code:: python\n\n >>> from schema import Forbidden\n >>> Schema({Forbidden('age'): object}).validate({'age': 50})\n Traceback (most recent call last):\n ...\n schema.SchemaForbiddenKeyError: Forbidden key encountered: 'age' in {'age': 50}\n\nA few things are worth noting. First, the value paired with the forbidden\nkey determines whether it will be rejected:\n\n.. code:: python\n\n >>> Schema({Forbidden('age'): str, 'age': int}).validate({'age': 50})\n {'age': 50}\n\nNote: if we hadn't supplied the 'age' key here, the call would have failed too, but with\nSchemaWrongKeyError, not SchemaForbiddenKeyError.\n\nSecond, Forbidden has a higher priority than standard keys, and consequently than Optional.\nThis means we can do that:\n\n.. code:: python\n\n >>> Schema({Forbidden('age'): object, Optional(str): object}).validate({'age': 50})\n Traceback (most recent call last):\n ...\n schema.SchemaForbiddenKeyError: Forbidden key encountered: 'age' in {'age': 50}\n\nYou can also define your own hooks. The following hook will call `_my_function` if `key` is encountered.\n\n.. code:: python\n\n from schema import Hook\n def _my_function(key, scope, error):\n print(key, scope, error)\n\n Hook(\"key\", handler=_my_function)\n\nHere's an example where a `Deprecated` class is added to log warnings whenever a key is encountered:\n\n.. code:: python\n\n from schema import Hook, Schema\n class Deprecated(Hook):\n def __init__(self, *args, **kwargs):\n kwargs[\"handler\"] = lambda key, *args: logging.warn(f\"`{key}` is deprecated. \" + (self._error or \"\"))\n super(Deprecated, self).__init__(*args, **kwargs)\n\n Schema({Deprecated(\"test\", \"custom error message.\"): object}, ignore_extra_keys=True).validate({\"test\": \"value\"})\n ...\n WARNING: `test` is deprecated. custom error message.\n\nExtra Keys\n~~~~~~~~~~\n\nThe ``Schema(...)`` parameter ``ignore_extra_keys`` causes validation to ignore extra keys in a dictionary, and also to not return them after validating.\n\n.. code:: python\n\n >>> schema = Schema({'name': str}, ignore_extra_keys=True)\n >>> schema.validate({'name': 'Sam', 'age': '42'})\n {'name': 'Sam'}\n\nIf you would like any extra keys returned, use ``object: object`` as one of the key/value pairs, which will match any key and any value.\nOtherwise, extra keys will raise a ``SchemaError``.\n\n\nCustomized Validation\n~~~~~~~~~~~~~~~~~~~~~~~\n\nThe ``Schema.validate`` method accepts additional keyword arguments. The\nkeyword arguments will be propagated to the ``validate`` method of any\nchild validatables (including any ad-hoc ``Schema`` objects), or the default\nvalue callable (if a callable is specified) for ``Optional`` keys.\n\nThis feature can be used together with inheritance of the ``Schema`` class\nfor customized validation.\n\nHere is an example where a \"post-validation\" hook that runs after validation\nagainst a sub-schema in a larger schema:\n\n.. code:: python\n\n class EventSchema(schema.Schema):\n\n def validate(self, data, _is_event_schema=True):\n data = super(EventSchema, self).validate(data, _is_event_schema=False)\n if _is_event_schema and data.get(\"minimum\", None) is None:\n data[\"minimum\"] = data[\"capacity\"]\n return data\n\n\n events_schema = schema.Schema(\n {\n str: EventSchema({\n \"capacity\": int,\n schema.Optional(\"minimum\"): int, # default to capacity\n })\n }\n )\n\n\n data = {'event1': {'capacity': 1}, 'event2': {'capacity': 2, 'minimum': 3}}\n events = events_schema.validate(data)\n\n assert events['event1']['minimum'] == 1 # == capacity\n assert events['event2']['minimum'] == 3\n\n\nNote that the additional keyword argument ``_is_event_schema`` is necessary to\nlimit the customized behavior to the ``EventSchema`` object itself so that it\nwon't affect any recursive invoke of the ``self.__class__.validate`` for the\nchild schemas (e.g., the call to ``Schema(\"capacity\").validate(\"capacity\")``).\n\n\nUser-friendly error reporting\n-------------------------------------------------------------------------------\n\nYou can pass a keyword argument ``error`` to any of validatable classes\n(such as ``Schema``, ``And``, ``Or``, ``Regex``, ``Use``) to report this error\ninstead of a built-in one.\n\n.. code:: python\n\n >>> Schema(Use(int, error='Invalid year')).validate('XVII')\n Traceback (most recent call last):\n ...\n schema.SchemaError: Invalid year\n\nYou can see all errors that occurred by accessing exception's ``exc.autos``\nfor auto-generated error messages, and ``exc.errors`` for errors\nwhich had ``error`` text passed to them.\n\nYou can exit with ``sys.exit(exc.code)`` if you want to show the messages\nto the user without traceback. ``error`` messages are given precedence in that\ncase.\n\nA JSON API example\n-------------------------------------------------------------------------------\n\nHere is a quick example: validation of\n`create a gist <http://developer.github.com/v3/gists/>`_\nrequest from github API.\n\n.. code:: python\n\n >>> gist = '''{\"description\": \"the description for this gist\",\n ... \"public\": true,\n ... \"files\": {\n ... \"file1.txt\": {\"content\": \"String file contents\"},\n ... \"other.txt\": {\"content\": \"Another file contents\"}}}'''\n\n >>> from schema import Schema, And, Use, Optional\n\n >>> import json\n\n >>> gist_schema = Schema(\n ... And(\n ... Use(json.loads), # first convert from JSON\n ... # use str since json returns unicode\n ... {\n ... Optional(\"description\"): str,\n ... \"public\": bool,\n ... \"files\": {str: {\"content\": str}},\n ... },\n ... )\n ... )\n\n >>> gist = gist_schema.validate(gist)\n\n # gist:\n {u'description': u'the description for this gist',\n u'files': {u'file1.txt': {u'content': u'String file contents'},\n u'other.txt': {u'content': u'Another file contents'}},\n u'public': True}\n\nUsing **schema** with `docopt <http://github.com/docopt/docopt>`_\n-------------------------------------------------------------------------------\n\nAssume you are using **docopt** with the following usage-pattern:\n\n Usage: my_program.py [--count=N] <path> <files>...\n\nand you would like to validate that ``<files>`` are readable, and that\n``<path>`` exists, and that ``--count`` is either integer from 0 to 5, or\n``None``.\n\nAssuming **docopt** returns the following dict:\n\n.. code:: python\n\n >>> args = {\n ... \"<files>\": [\"LICENSE-MIT\", \"setup.py\"],\n ... \"<path>\": \"../\",\n ... \"--count\": \"3\",\n ... }\n\nthis is how you validate it using ``schema``:\n\n.. code:: python\n\n >>> from schema import Schema, And, Or, Use\n >>> import os\n\n >>> s = Schema({\n ... \"<files>\": [Use(open)],\n ... \"<path>\": os.path.exists,\n ... \"--count\": Or(None, And(Use(int), lambda n: 0 < n < 5)),\n ... })\n\n\n >>> args = s.validate(args)\n\n >>> args['<files>']\n [<_io.TextIOWrapper name='LICENSE-MIT' ...>, <_io.TextIOWrapper name='setup.py' ...]\n\n >>> args['<path>']\n '../'\n\n >>> args['--count']\n 3\n\nAs you can see, **schema** validated data successfully, opened files and\nconverted ``'3'`` to ``int``.\n\nJSON schema\n-----------\n\nYou can also generate standard `draft-07 JSON schema <https://json-schema.org/>`_ from a dict ``Schema``.\nThis can be used to add word completion, validation, and documentation directly in code editors.\nThe output schema can also be used with JSON schema compatible libraries.\n\nJSON: Generating\n~~~~~~~~~~~~~~~~\n\nJust define your schema normally and call ``.json_schema()`` on it. The output is a Python dict, you need to dump it to JSON.\n\n.. code:: python\n\n >>> from schema import Optional, Schema\n >>> import json\n >>> s = Schema({\n ... \"test\": str,\n ... \"nested\": {Optional(\"other\"): str},\n ... })\n >>> json_schema = json.dumps(s.json_schema(\"https://example.com/my-schema.json\"))\n\n # json_schema\n {\n \"type\":\"object\",\n \"properties\": {\n \"test\": {\"type\": \"string\"},\n \"nested\": {\n \"type\":\"object\",\n \"properties\": {\n \"other\": {\"type\": \"string\"}\n },\n \"required\": [],\n \"additionalProperties\": false\n }\n },\n \"required\":[\n \"test\",\n \"nested\"\n ],\n \"additionalProperties\":false,\n \"$id\":\"https://example.com/my-schema.json\",\n \"$schema\":\"http://json-schema.org/draft-07/schema#\"\n }\n\nYou can add descriptions for the schema elements using the ``Literal`` object instead of a string. The main schema can also have a description.\n\nThese will appear in IDEs to help your users write a configuration.\n\n.. code:: python\n\n >>> from schema import Literal, Schema\n >>> import json\n >>> s = Schema(\n ... {Literal(\"project_name\", description=\"Names must be unique\"): str},\n ... description=\"Project schema\",\n ... )\n >>> json_schema = json.dumps(s.json_schema(\"https://example.com/my-schema.json\"), indent=4)\n\n # json_schema\n {\n \"type\": \"object\",\n \"properties\": {\n \"project_name\": {\n \"description\": \"Names must be unique\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"project_name\"\n ],\n \"additionalProperties\": false,\n \"$id\": \"https://example.com/my-schema.json\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"description\": \"Project schema\"\n }\n\n\nJSON: Supported validations\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe resulting JSON schema is not guaranteed to accept the same objects as the library would accept, since some validations are not implemented or\nhave no JSON schema equivalent. This is the case of the ``Use`` and ``Hook`` objects for example.\n\nImplemented\n'''''''''''\n\n`Object properties <https://json-schema.org/understanding-json-schema/reference/object.html#properties>`_\n Use a dict literal. The dict keys are the JSON schema properties.\n\n Example:\n\n ``Schema({\"test\": str})``\n\n becomes\n\n ``{'type': 'object', 'properties': {'test': {'type': 'string'}}, 'required': ['test'], 'additionalProperties': False}``.\n\n Please note that attributes are required by default. To create optional attributes use ``Optional``, like so:\n\n ``Schema({Optional(\"test\"): str})``\n\n becomes\n\n ``{'type': 'object', 'properties': {'test': {'type': 'string'}}, 'required': [], 'additionalProperties': False}``\n\n additionalProperties is set to true when at least one of the conditions is met:\n - ignore_extra_keys is True\n - at least one key is `str` or `object`\n\n For example:\n\n ``Schema({str: str})`` and ``Schema({}, ignore_extra_keys=True)``\n\n both becomes\n\n ``{'type': 'object', 'properties' : {}, 'required': [], 'additionalProperties': True}``\n\n and\n\n ``Schema({})``\n\n becomes\n\n ``{'type': 'object', 'properties' : {}, 'required': [], 'additionalProperties': False}``\n\nTypes\n Use the Python type name directly. It will be converted to the JSON name:\n\n - ``str`` -> `string <https://json-schema.org/understanding-json-schema/reference/string.html>`_\n - ``int`` -> `integer <https://json-schema.org/understanding-json-schema/reference/numeric.html#integer>`_\n - ``float`` -> `number <https://json-schema.org/understanding-json-schema/reference/numeric.html#number>`_\n - ``bool`` -> `boolean <https://json-schema.org/understanding-json-schema/reference/boolean.html>`_\n - ``list`` -> `array <https://json-schema.org/understanding-json-schema/reference/array.html>`_\n - ``dict`` -> `object <https://json-schema.org/understanding-json-schema/reference/object.html>`_\n\n Example:\n\n ``Schema(float)``\n\n becomes\n\n ``{\"type\": \"number\"}``\n\n`Array items <https://json-schema.org/understanding-json-schema/reference/array.html#items>`_\n Surround a schema with ``[]``.\n\n Example:\n\n ``Schema([str])`` means an array of string and becomes:\n\n ``{'type': 'array', 'items': {'type': 'string'}}``\n\n`Enumerated values <https://json-schema.org/understanding-json-schema/reference/generic.html#enumerated-values>`_\n Use `Or`.\n\n Example:\n\n ``Schema(Or(1, 2, 3))`` becomes\n\n ``{\"enum\": [1, 2, 3]}``\n\n`Constant values <https://json-schema.org/understanding-json-schema/reference/generic.html#constant-values>`_\n Use the value itself.\n\n Example:\n\n ``Schema(\"name\")`` becomes\n\n ``{\"const\": \"name\"}``\n\n`Regular expressions <https://json-schema.org/understanding-json-schema/reference/regular_expressions.html>`_\n Use ``Regex``.\n\n Example:\n\n ``Schema(Regex(\"^v\\d+\"))`` becomes\n\n ``{'type': 'string', 'pattern': '^v\\\\d+'}``\n\n`Annotations (title and description) <https://json-schema.org/understanding-json-schema/reference/generic.html#annotations>`_\n You can use the ``name`` and ``description`` parameters of the ``Schema`` object init method.\n\n To add description to keys, replace a str with a ``Literal`` object.\n\n Example:\n\n ``Schema({Literal(\"test\", description=\"A description\"): str})``\n\n is equivalent to\n\n ``Schema({\"test\": str})``\n\n with the description added to the resulting JSON schema.\n\n`Combining schemas with allOf <https://json-schema.org/understanding-json-schema/reference/combining.html#allof>`_\n Use ``And``\n\n Example:\n\n ``Schema(And(str, \"value\"))``\n\n becomes\n\n ``{\"allOf\": [{\"type\": \"string\"}, {\"const\": \"value\"}]}``\n\n Note that this example is not really useful in the real world, since ``const`` already implies the type.\n\n`Combining schemas with anyOf <https://json-schema.org/understanding-json-schema/reference/combining.html#anyof>`_\n Use ``Or``\n\n Example:\n\n ``Schema(Or(str, int))``\n\n becomes\n\n ``{\"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]}``\n\n\nNot implemented\n'''''''''''''''\n\nThe following JSON schema validations cannot be generated from this library.\n\n- `String length <https://json-schema.org/understanding-json-schema/reference/string.html#length>`_\n However, those can be implemented using ``Regex``\n- `String format <https://json-schema.org/understanding-json-schema/reference/string.html#format>`_\n However, those can be implemented using ``Regex``\n- `Object dependencies <https://json-schema.org/understanding-json-schema/reference/object.html#dependencies>`_\n- `Array length <https://json-schema.org/understanding-json-schema/reference/array.html#length>`_\n- `Array uniqueness <https://json-schema.org/understanding-json-schema/reference/array.html#uniqueness>`_\n- `Numeric multiples <https://json-schema.org/understanding-json-schema/reference/numeric.html#multiples>`_\n- `Numeric ranges <https://json-schema.org/understanding-json-schema/reference/numeric.html#range>`_\n- `Property Names <https://json-schema.org/understanding-json-schema/reference/object.html#property-names>`_\n Not implemented. We suggest listing the possible keys instead. As a tip, you can use ``Or`` as a dict key.\n\n Example:\n\n ``Schema({Or(\"name1\", \"name2\"): str})``\n- `Annotations (default and examples) <https://json-schema.org/understanding-json-schema/reference/generic.html#annotations>`_\n- `Combining schemas with oneOf <https://json-schema.org/understanding-json-schema/reference/combining.html#oneof>`_\n- `Not <https://json-schema.org/understanding-json-schema/reference/combining.html#not>`_\n- `Object size <https://json-schema.org/understanding-json-schema/reference/object.html#size>`_\n- `additionalProperties having a different schema (true and false is supported)`\n\n\nJSON: Minimizing output size\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nExplicit Reuse\n''''''''''''''\n\nIf your JSON schema is big and has a lot of repetition, it can be made simpler and smaller by defining Schema objects as reference.\nThese references will be placed in a \"definitions\" section in the main schema.\n\n`You can look at the JSON schema documentation for more information <https://json-schema.org/understanding-json-schema/structuring.html#reuse>`_\n\n.. code:: python\n\n >>> from schema import Optional, Schema\n >>> import json\n >>> s = Schema({\n ... \"test\": str,\n ... \"nested\": Schema({Optional(\"other\"): str}, name=\"nested\", as_reference=True)\n ... })\n >>> json_schema = json.dumps(s.json_schema(\"https://example.com/my-schema.json\"), indent=4)\n\n # json_schema\n {\n \"type\": \"object\",\n \"properties\": {\n \"test\": {\n \"type\": \"string\"\n },\n \"nested\": {\n \"$ref\": \"#/definitions/nested\"\n }\n },\n \"required\": [\n \"test\",\n \"nested\"\n ],\n \"additionalProperties\": false,\n \"$id\": \"https://example.com/my-schema.json\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"definitions\": {\n \"nested\": {\n \"type\": \"object\",\n \"properties\": {\n \"other\": {\n \"type\": \"string\"\n }\n },\n \"required\": [],\n \"additionalProperties\": false\n }\n }\n }\n\nThis becomes really useful when using the same object several times\n\n.. code:: python\n\n >>> from schema import Optional, Or, Schema\n >>> import json\n >>> language_configuration = Schema(\n ... {\"autocomplete\": bool, \"stop_words\": [str]},\n ... name=\"language\",\n ... as_reference=True,\n ... )\n >>> s = Schema({Or(\"ar\", \"cs\", \"de\", \"el\", \"eu\", \"en\", \"es\", \"fr\"): language_configuration})\n >>> json_schema = json.dumps(s.json_schema(\"https://example.com/my-schema.json\"), indent=4)\n\n # json_schema\n {\n \"type\": \"object\",\n \"properties\": {\n \"ar\": {\n \"$ref\": \"#/definitions/language\"\n },\n \"cs\": {\n \"$ref\": \"#/definitions/language\"\n },\n \"de\": {\n \"$ref\": \"#/definitions/language\"\n },\n \"el\": {\n \"$ref\": \"#/definitions/language\"\n },\n \"eu\": {\n \"$ref\": \"#/definitions/language\"\n },\n \"en\": {\n \"$ref\": \"#/definitions/language\"\n },\n \"es\": {\n \"$ref\": \"#/definitions/language\"\n },\n \"fr\": {\n \"$ref\": \"#/definitions/language\"\n }\n },\n \"required\": [],\n \"additionalProperties\": false,\n \"$id\": \"https://example.com/my-schema.json\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"definitions\": {\n \"language\": {\n \"type\": \"object\",\n \"properties\": {\n \"autocomplete\": {\n \"type\": \"boolean\"\n },\n \"stop_words\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"autocomplete\",\n \"stop_words\"\n ],\n \"additionalProperties\": false\n }\n }\n }\n\nAutomatic reuse\n'''''''''''''''\n\nIf you want to minimize the output size without using names explicitly, you can have the library generate hashes of parts of the output JSON\nschema and use them as references throughout.\n\nEnable this behaviour by providing the parameter ``use_refs`` to the json_schema method.\n\nBe aware that this method is less often compatible with IDEs and JSON schema libraries.\nIt produces a JSON schema that is more difficult to read by humans.\n\n.. code:: python\n\n >>> from schema import Optional, Or, Schema\n >>> import json\n >>> language_configuration = Schema({\"autocomplete\": bool, \"stop_words\": [str]})\n >>> s = Schema({Or(\"ar\", \"cs\", \"de\", \"el\", \"eu\", \"en\", \"es\", \"fr\"): language_configuration})\n >>> json_schema = json.dumps(s.json_schema(\"https://example.com/my-schema.json\", use_refs=True), indent=4)\n\n # json_schema\n {\n \"type\": \"object\",\n \"properties\": {\n \"ar\": {\n \"type\": \"object\",\n \"properties\": {\n \"autocomplete\": {\n \"type\": \"boolean\",\n \"$id\": \"#6456104181059880193\"\n },\n \"stop_words\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"$id\": \"#1856069563381977338\"\n }\n }\n },\n \"required\": [\n \"autocomplete\",\n \"stop_words\"\n ],\n \"additionalProperties\": false\n },\n \"cs\": {\n \"type\": \"object\",\n \"properties\": {\n \"autocomplete\": {\n \"$ref\": \"#6456104181059880193\"\n },\n \"stop_words\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#1856069563381977338\"\n },\n \"$id\": \"#-5377945144312515805\"\n }\n },\n \"required\": [\n \"autocomplete\",\n \"stop_words\"\n ],\n \"additionalProperties\": false\n },\n \"de\": {\n \"type\": \"object\",\n \"properties\": {\n \"autocomplete\": {\n \"$ref\": \"#6456104181059880193\"\n },\n \"stop_words\": {\n \"$ref\": \"#-5377945144312515805\"\n }\n },\n \"required\": [\n \"autocomplete\",\n \"stop_words\"\n ],\n \"additionalProperties\": false,\n \"$id\": \"#-8142886105174600858\"\n },\n \"el\": {\n \"$ref\": \"#-8142886105174600858\"\n },\n \"eu\": {\n \"$ref\": \"#-8142886105174600858\"\n },\n \"en\": {\n \"$ref\": \"#-8142886105174600858\"\n },\n \"es\": {\n \"$ref\": \"#-8142886105174600858\"\n },\n \"fr\": {\n \"$ref\": \"#-8142886105174600858\"\n }\n },\n \"required\": [],\n \"additionalProperties\": false,\n \"$id\": \"https://example.com/my-schema.json\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n }\n\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Simple data validation library",
"version": "0.7.7",
"project_urls": {
"Homepage": "https://github.com/keleshev/schema"
},
"split_keywords": [
"schema",
"json",
"validation"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "ad1b81855a88c6db2b114d5b2e9f96339190d5ee4d1b981d217fa32127bb00e0",
"md5": "c33798aa864147ad740e4d120a0a30d0",
"sha256": "5d976a5b50f36e74e2157b47097b60002bd4d42e65425fcc9c9befadb4255dde"
},
"downloads": -1,
"filename": "schema-0.7.7-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "c33798aa864147ad740e4d120a0a30d0",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": null,
"size": 18632,
"upload_time": "2024-05-04T10:56:13",
"upload_time_iso_8601": "2024-05-04T10:56:13.860579Z",
"url": "https://files.pythonhosted.org/packages/ad/1b/81855a88c6db2b114d5b2e9f96339190d5ee4d1b981d217fa32127bb00e0/schema-0.7.7-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "d4010ea2e66bad2f13271e93b729c653747614784d3ebde219679e41ccdceecd",
"md5": "663e981a0cf4e954b4ce3c68dbc42f64",
"sha256": "7da553abd2958a19dc2547c388cde53398b39196175a9be59ea1caf5ab0a1807"
},
"downloads": -1,
"filename": "schema-0.7.7.tar.gz",
"has_sig": false,
"md5_digest": "663e981a0cf4e954b4ce3c68dbc42f64",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 44245,
"upload_time": "2024-05-04T10:56:17",
"upload_time_iso_8601": "2024-05-04T10:56:17.318461Z",
"url": "https://files.pythonhosted.org/packages/d4/01/0ea2e66bad2f13271e93b729c653747614784d3ebde219679e41ccdceecd/schema-0.7.7.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-05-04 10:56:17",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "keleshev",
"github_project": "schema",
"travis_ci": true,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "contextlib2",
"specs": [
[
">=",
"0.5.5"
]
]
}
],
"tox": true,
"lcname": "schema"
}