Skip to main content

Flask extension to validate JSON requests

Project description

Flask-json-schema

This extension makes it easy to validate JSON data that is sent to your Flask app using the jsonschema spec

Setup

Flask-json-schema is available on PyPI and can be installed with

pip install flask-json-schema

The extension can either be initialized directly:

from flask import Flask
from flask_json_schema import JsonSchema

app = Flask(__name__)
schema = JsonSchema(app)

Or through the factory method:

schema = JsonSchema()

app = Flask(__name__)
schema.init_app(app)

Quick example

from flask_json_schema import JsonSchema, JsonValidationError
from flask import Flask, jsonify, request

app = Flask(__name__)
schema = JsonSchema(app)

todo_schema = {
    'required': ['todo'],
    'properties': {
        'todo': { 'type': 'string' },
        'priority': { 'type': 'integer' },
    }
}

todos = []

@app.errorhandler(JsonValidationError)
def validation_error(e):
    return jsonify({ 'error': e.message, 'errors': [validation_error.message for validation_error  in e.errors]})

@app.route('/todo', methods=['GET', 'POST'])
@schema.validate(todo_schema)
def create_message():
    if request.method == 'POST':
        todos.append( request.get_json() )
        return jsonify({ 'success': True, 'message': 'Created todo' })

    return jsonify(todos)

app.run('0.0.0.0', 5000, debug=True)

See example.py for the source code

Links

Project details


Download files

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

Filename, size & hash SHA256 hash help File type Python version Upload date
Flask_json_schema-0.0.5-py3-none-any.whl (2.9 kB) Copy SHA256 hash SHA256 Wheel py3
Flask-json-schema-0.0.5.tar.gz (2.7 kB) Copy SHA256 hash SHA256 Source None

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page