Decorator for REST endpoints in flask. Validate JSON request data.
Project description
flask-expects-json
Decorator for REST endpoints in flask. Validate JSON request data.
When building json REST services I find myself already specifying json-schema for POST data while defining swagger spec. This package brings json validation to flask. It omits the need to validate the data yourself while profiting from an already established standard (http://json-schema.org/). Defining the schema right before the route helps the self-documentation of an endpoint (see usage).
This package uses jsonschema to for validation: https://pypi.python.org/pypi/jsonschema
Usage
This package provides a flask route decorator to validate json payload.
from flask import Flask, jsonify, g, url_for
from flask_expects_json import expects_json
# example imports
from models import User
from orm import NotUniqueError
app = Flask(__name__)
schema = {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'email': {'type': 'string'},
'password': {'type': 'string'}
},
'required': ['email', 'password']
}
@app.route('/register', methods=['POST'])
@expects_json(schema)
def register():
# if payload is invalid, request will be aborted with error code 400
# if payload is valid it is stored in g.data
# do something with your data
user = User().from_dict(g.data)
try:
user.save()
except NotUniqueError as e:
# exception path: duplicate database entry
return jsonify(dict(message=e.message)), 409
# happy path: json response
resp = jsonify(dict(auth_token=user.encode_auth_token(), user=user.to_dict()})
resp.headers['Location'] = url_for('users.get_user', user_id=user.id)
return resp, 201
The expected json payload is recognizable through “schema”. If schema is not met the requests aborts (400) with a hinting error message.
flask.request.get_json(force=True) is used to get the data. This means the mimetype of the request is ignored.
Note on self-documentation: all input and output possibilities are clearly visible in this snippet.
Default values
Normally validators wont touch the data. By default this package will fill in missing default values provided in the schema. The validation will be performed after this action, so default values can lead to invalid data. If you dont want this behavior set fill_defaults=False as a paramter to expects_json.
Testing
python setup.py test
ToDo
Insert default values in data if none provided.
Changelog
Unreleased
1.1.0 - 2018-02-03
Added
missing default values will be filled into the request data
can be turned off via fill_defaults=False
1.0.6 - 2018-01-29
Code-style/readme changes.
Add tests for Python 3.4, 3.5, 3.6
Changes made for proper CI and automatic release
Add code coverage
1.0.0 - 2018-01-21
Added
Initial version of expects_json() decorator
Simple validation of request data
Store data in g.data
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file flask-expects-json-1.1.0.tar.gz
.
File metadata
- Download URL: flask-expects-json-1.1.0.tar.gz
- Upload date:
- Size: 4.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1b5ebe71dcad9e00e33ee7fc456ced7661f15b036850a29fc962080f850e0fdd |
|
MD5 | daaff7decfadfbf49ec196419eac3381 |
|
BLAKE2b-256 | 2712e5e2578d047ce42aad8cfa48270a1e2fe4f9af7c7f8386868ed83cfddef9 |