Decorator for endpoint inputs on APIs and a dictionary/JSON validator.
Project description
pyschemavalidator
Decorator for endpoints in flask and a way to validate dictionary/JSON elements.
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 by defining all the element restrictions using decorators or not.
Installation
Use pip to install the package from PyPI:
pip install pyschemavalidator
Usage
This package provides a flask route decorator to validate the json payload.
from flask import Flask, make_response, jsonify, g, url_for
from pyschemavalidator import validate_param
# example imports
from models import Model
app = Flask(__name__)
@app.route('/invocations', methods=['POST'])
@validate_param(key="sepal_length", keytype=float, isrequired=True)
@validate_param(key="sepal_width", keytype=float, isrequired=True)
@validate_param(key="petal_length", keytype=float, isrequired=True)
@validate_param(key="petal_width", keytype=float, isrequired=True)
def register():
# if payload is invalid, request will be aborted with the appropriate error code
# do model inference
data = request.get_json(silent=True, force=False)
output = Model.predict(data.get('sepal_length'), data.get('sepal_width'), data.get('petal_length'), data.get('petal_width'))
return make_response(jsonify({"output:": output}), 200)
The payload is verified thought the parameters set on the decorators. If body does not met the decorator speficications it returns a standard response with the appropriate error code.
You can also use the package without the decorator style as above:
from pyschemavalidator.validators import UniversalValidator
# Creates a Universal validator to the dictionary/JSON elements
request_validator = UniversalValidator()
request_validator.add(key="example1", keytype=str, isrequired=True)
request_validator.add(key="example2", keytype=str, isrequired=False)
# Example data
data = {"example1": "test", "example2": "test"}
# Add some validations to the JSON/dictionary element
status_code, message = request_validator.validate(
tag1=data.get("example1"),
tag2=data.get("example2")
)
if status_code != 200: # It means that something got wrong from the validation
raise ValueError(message)
else
... # Do whatever you want
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'.
Error handling
On validation failure the library calls flask.abort
and passes an 400 error code and the validation error.
By default this creates an HTML error page and displays the error message.
To customize the behavior use the error handling provided by flask (docs).
This can be useful to e.g hide the validation message from users or provide a JSON response.
The original ValidationError is passed to flask.abort
, which itself passes arguments to werkzeug.exceptions.HTTPException
so it can be retrieved on error.description
like this:
Testing
The following are the steps to create a virtual environment into a folder named "venv" and install the requirements.
# Create virtualenv
python3 -m venv venv
# activate virtualenv
source venv/bin/activate
# update packages
pip install --upgrade pip setuptools wheel
# install requirements
python setup.py install
Tests can be run with python setup.py test
when the virtualenv is active.
Changelog
Unreleased
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
Built Distribution
Hashes for pyschemavalidator-1.0.1-py2-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4a84f48c0e33588f901e700e7562b1f4765908c8dbfe46aff4eaaf85949b95d9 |
|
MD5 | 99d0548ef3c878e91fc3cd4f5be098b3 |
|
BLAKE2b-256 | 5ae1e137142dcd1de7ff7e2660790ad064a517e74dbe69eac61901428e89b4a2 |