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)
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.
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.
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.
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.
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
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With