1. Timothy Corbett-Clark
  2. rest-api-blueprint

Wiki

Clone wiki

rest-api-blueprint / IncomingData

Validating and marshalling incoming data

Clearly one needs to be careful to validate input data structures. Given that we are using JSON, this seems like a good choice:

There is at least one Python implementation, e.g.:

However we also want to be able to marshal input types such as datetimes and tuples (neither of which are supported in JSON).

We could use something like:

However it makes things a little too Python specific, and the structure still needs to be validated.

For now at least, I am going to use:

This supports validation of input structure (with some limitations of accurate error messages with optional arguments), at the same time as supporting type marshalling.

So for example, we can use this to marshal tuples from lists and marshal iso8601 datetimes from string representations using isodate as follows:

import isodate
from schema import (Schema, Use, And)

s = Schema(
    {
        'a_date': Use(isodate.parse_datetime),
        'a_tuple_of_ints': And(Use(tuple), (int,))
    }
)

Then

>>>print s.validate(
    {
        'a_date': '2012-09-23T18:51:13.957050',
        'a_tuple_of_ints': [1, 2, 3]
    }
)

{'a_tuple_of_ints': (1, 2, 3), 'a_date': datetime.datetime(2012, 9, 23, 18, 51, 13, 957050)}

But

>>>print s.validate(
    {
        'a_date': '2012-09-23T18:51:13.957050',
        'a_tuple_of_ints': [1, 2, '3']
    }
)

Traceback (most recent call last):
  File "/home/tcorbettclark/test.py", line 14, in <module>
    'a_tuple_of_ints': [1, 2, '3']
  File "/home/tcorbettclark/.virtualenvs/flask/local/lib/python2.7/site-packages/schema.py", line 110, in validate
    x.autos, [e] + x.errors)
schema.SchemaError: key 'a_tuple_of_ints' is required
Or(<type 'int'>) did not validate '3'
'3' should be instance of <type 'int'>

Updated