Flex is a Swagger 2.0 validator. It is stable but at this point its development is in maintenance mode. However, we do accept all types of pull requests, so please get involved at GitHub!
install flex
$ pip install flex
Then in your code.
import flex
schema = flex.load('path/to/schema.yaml')
The flex.load
function supports the following.
- A url to either a
json
oryaml
schema. - A path to either a
json
oryaml
schema. - A file object whose contents are
json
oryaml
- A string whose contents are
json
oryaml
- A native python object that is a
Mapping
(like a dictionary).
A subset of the flex
tooling implements JSON schema validation.
>>> from flex.core import validate
>>> schema = {
...: 'properties': {
...: 'name': {
...: 'type': 'string',
...: 'minLength': 3,
...: },
...: 'age': {
...: 'type': 'integer',
...: 'minimum': 0,
...: 'exclusiveMinimum': True,
...: },
...: }
...: }
>>> data = {
...: 'age': 10,
...: 'name': "John",
...: }
>>> validate(schema, data)
>>> bad_data = {
...: 'age': -5,
...: 'name': "Bo",
...: }
>>> validate(schema, bad_data)
ValueError: Invalid:
'age':
- 'minimum':
- u'-5 must be greater than 0.0'
'name':
- 'minLength':
- u'Ensure this value has at least 3 characters (it has 2).'
You can also use this to simply validate that your JSON schema conforms to specification.
>>> from flex.core import validate
>>> schema = {
...: 'properties': {
...: 'name': {
...: 'type': 'string',
...: 'minLength': 3,
...: },
...: 'friends': {
...: 'type': 'array',
...: 'minimum': 0, # `minimum` is invalid for type 'array'
...: },
...: }
...: }
>>> validate(schema)
ValueError: JSON Schema did not validate:
u'properties':
- 'friends':
- 'minimum':
- u'`minimum` can only be used for json number types'
API call validation takes a supported request and response object that represents a request/response cycle for an API call and validates it against a swagger schema.
>>> import requests
>>> from flex.core import load, validate_api_call
>>> schema = load("path/to/schema.yaml")
>>> response = requests.get('http://www.example.com/api/')
>>> validate_api_call(schema, raw_request=response.request, raw_response=response)
ValueError: Invalid
'response':
- 'Request status code was not found in the known response codes. Got `301`: Expected one of: `[200]`'
Request validation looks at the following things.
- Request path.
- Parameters in the path.
- Query parameters.
- Request method.
- Headers.
- Content Type
Response validation looks at the following things.
- Content-Type
- Headers
- Status Code
- Response body.
Request validation supports the following request objects.
requests.Request
andrequests.PreparedRequest
from Kenneth Reitz'requests
library.urllib2.Request
from theurllib2
module of the standard library.django.http.request.HttpRequest
fromdjango
.werkzeug.wrappers.Request
fromwerkzeug
(on whichflask
is based).
Response valdation supports the following respone objects.
requests.Response
from Kenneth Reitz'requests
library.- The return value of
urllib.urlopen
andurllib2.urlopen
from the standard library urllib modules. django.http.response.HttpResponse
fromdjango
.werkzeug.wrappers.Response
fromwerkzeug
(on whichflask
is based).
Flex implements format validation for the following formats
uuid
: Version 1, 3, 4, and 5datetime
: RFC3339 formatted datetimes via https://pypi.python.org/pypi/strict-rfc3339.int32
: Integers up to 32 bits.int64
: Integers up to 64 bits.email
: via https://pypi.python.org/pypi/validate_emailuri
: via https://pypi.python.org/pypi/rfc3987
Flex supports registering your own custom formats for validation.
>>> from flex.formats import register
>>> @register('title-case', 'string')
... def title_case_format_validator(value):
... if not value == value.title():
... raise ValidationError("Must be title cased")
In the example above, we have registered a new format title-case
which is
applicable to values of type string. A validator function needs to take a
single value and raise a ValidationError
if the value is invalid.
The register
decorator takes the name of the format as it's first argument,
and then the remaining arguments should be the types that the format validator
can apply to.
Note
Take note that format validation is skipped if the value is not of one of the specified types the format validator is declared for.
As well as a python API, flex
also provides a commandline validation tool via the swagger-flex
cli.
$ ./swagger-flex -s /path/to/swagger.yaml
$ ./swagger-flex -s http://spec.example.com/swagger.yaml
In the event of a validation error, the commandline program will return 1 and print to stderr a list of the validation errors detected.
If the file passes validation it will return to stdout "Validation passed" and return 0 - in line with most nix commandline tools.
Contents:
.. toctree:: :maxdepth: 2