Skip to main content

Decorator for REST endpoints in flask. Validate JSON request data.

Project description

version license pyversions pipeline status coverage

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.

Mimetype checking

As of 1.2.0 this decorator uses flask.request.get_json(force=False) to get the data. This means the mimetype of the request has to be 'application/json'. Can be disabled by setting force=False. Be aware that this creates a major security vulnerability to CSRF since CORS is not enforced for certain mimetypes. Thanks to Argishti Rostamian for noticing.

@app.route('/strict')
@expects_json()
def strict():
    return 'This view will return 400 if mimetype is not \'application/json\' 

@app.route('/insecure')
@expects_json({}, force=False)
def insecure():
    return 'This view will validate the data no matter the mimetype.'

Default values

Normally validators wont touch the data. By default this package will not fill in missing default values provided in the schema. If you want to you can set fill_defaults=True explicitly. The validation will be performed after this action, so default values can lead to invalid data.

Skip validation methods

If you want to skip the validation for certain HTTP methods, specify them with ignore_for=[]. Typical methods that do not expect a body are GET, HEAD and DELETE. Thanks to @mtheos for implementing this.

@app.route('/', methods=['GET', 'POST'])
@expects_json(schema, ignore_for=['GET'])
def register():
    return 

Testing

python setup.py test

Changelog

Unreleased

1.5.0 - 2020-08-24

  • Feature: ignore validation for certain HTTP methods. (thanks @mtheos)

1.4.0 - 2019-09-02

  • Updated dependencies to new major versions.
  • Removed Python 3.4 support (as jsonschema did)
  • Fixed: Typo in readme
  • Changed: Pass whole error object to the 400 abort on schema validation error

1.3.1

  • Changed error message when get_json() fails.
  • Bugfix in DefaultValidatingDraft4Validator when trying to set a default value on strings.

1.3.0 - 2018-02-16

  • Changed: Defaults wont be filled in request data by default. Set fill_defaults=True explicitly.

1.2.0 - 2018-02-15

  • Security: set force=False as default argument for mimetype checking. Before: force=True for convenience

1.1.0 - 2018-02-03

  • Added missing default values will be automatically filled into the request data
  • Added parameter fill_defaults

1.0.6 - 2018-01-29

  • Added tests for Python 3.4, 3.5, 3.6
  • Added code coverage
  • Changed code-style/readme.

1.0.0 - 2018-01-21

  • Added initial version of expects_json() decorator
  • Added simple validation of request data
  • Added store data in g.data

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask-expects-json-1.5.0.tar.gz (5.1 kB view details)

Uploaded Source

Built Distributions

flask_expects_json-1.5.0-py3.8.egg (6.3 kB view details)

Uploaded Source

flask_expects_json-1.5.0-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

Details for the file flask-expects-json-1.5.0.tar.gz.

File metadata

  • Download URL: flask-expects-json-1.5.0.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.7.5

File hashes

Hashes for flask-expects-json-1.5.0.tar.gz
Algorithm Hash digest
SHA256 0087dc3d089f1ac75a1fc0f259f4dbd02bbb9c356e92e1a080f2309e2f75d053
MD5 c1fb8ede58db312d7923212dc97b8ab4
BLAKE2b-256 4c4a9d9d050af700fb3feebd1f8466e73d65ce8b4709f27773e07100b0993451

See more details on using hashes here.

File details

Details for the file flask_expects_json-1.5.0-py3.8.egg.

File metadata

  • Download URL: flask_expects_json-1.5.0-py3.8.egg
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.6.3 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.9.5

File hashes

Hashes for flask_expects_json-1.5.0-py3.8.egg
Algorithm Hash digest
SHA256 b26bce48ca7cb3c42bf977b347ce6f4fab926073ee10406a9b147199c7f0434b
MD5 b1c8ad4007adcb61bcfc6df7039306bc
BLAKE2b-256 de74d8b9bedf0b2ffad04ad45249b6f4259d9c0598caafaa9b2ff103843b01b0

See more details on using hashes here.

File details

Details for the file flask_expects_json-1.5.0-py3-none-any.whl.

File metadata

  • Download URL: flask_expects_json-1.5.0-py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.7.5

File hashes

Hashes for flask_expects_json-1.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5aa33f50f7363592a0564fdd9e45b941b45d9683316fd654bd5062bf4b564edb
MD5 c04f647e601c58daf267417dd013d5a6
BLAKE2b-256 258840cd66aad9423b88c92cb6835324d471430d3e78d29a902ed4457ccfcf31

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page