Sanic-validation 0.3 brings support for data normalization

Sanic-validation 0.3.0 was just released.
A big new feature is support for data normalization. You can have cleaned and normalized data provided directly to your handler method. Renaming of fields, assigning default values and converting types could be done as part of the validation step. This is especially useful for working with query arguments, as they are provided as strings by default.

How to use it?

Let’s say we want to write a service that returns the first count words of Lorem Ipsum. Let’s also assume that we have a list lorem_ipsum_words containing the text split into single words.
Our endpoint could look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
schema = {
'count': {
'type': 'integer',
'min': 1,
'required': True,
'coerce': int,
}
}


@app.get('/lorem-provider')
@validate_args(schema, clean=True)
async def lorem_ipsum_provider(request, valid_args):
words = lorem_ipsum_words[:valid_args['count']]
result = ' '.join(words)
return text(result)

Because of the coerce rule, count will be parsed with int before validation begins. If conversion fails, an appropriate validation error will be returned. Enabling the clean flag signals that we want cleaned arguments to be passed to our handler function as valid_args. This dictionary will contain count as a number, so we don’t have to manually convert it.

For more information, check out the documentation.