Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request json validation in the flask

Is there some best practice how to validate json request in Flask? There is interesting approach in the Flask restful extension but I don't need it in my app. I just want to have something like this:

user_schema = {
    'username': email,
    'password': required,
    'age': required
}


@app.route('new_user/', methods=['POST'])
def new_user():
    validate_json(request.json, user_schema)
like image 399
Alexander Avatar asked Mar 09 '16 18:03

Alexander


People also ask

How do I request JSON data in Flask?

Approach 1: Using Flask jsonify object – In this approach, we are going to return a JSON response using the flask jsonify method. We are not going to use the flask-restful library in this method. Create a new python file named 'main.py'. import Flask, jsonify, and request from the flask framework.

How do I validate a JSON request?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

How do you validate a body request in Flask?

To do request JSON validation, first I have to parse received input JSON data, parse its JSON body, validate each then reconstructs it as JSON object, and pass to the API function.

How do you send a JSON response to a Flask?

There are two methods you can use to return JSON data in your Flask application's view: by returning a Python dictionary, or by using Flask's jsonify() method.


1 Answers

Take a look at cerberus

Example usage:

>>> from cerberus import Validator
>>> schema = {'name': {'type': 'string', 'required': True}}
>>> v = Validator(schema)
>>> document = {'bla': 'john doe'}
>>> v.validate(document)
False
>>>
like image 60
nguyên Avatar answered Oct 04 '22 23:10

nguyên