Issue
I am using the flask framework in my new project. It would get JSON data from the post and send a JSON response. So, I need to validate my JSON request.
I have seen couple of libraries. But those libraries are not working as expected. Finally, I have decided to go with a flask-jsonschema-validator
. It is working fine with a single JSON object. If the request object has a nested object, it is not working.
For example:
from flask_jsonschema_validator import JSONSchemaValidator
JSONSchemaValidator(app=app, root="schemas")
This is my initialization of the validator:
# If any error occurred in the request.
@app.errorhandler(jsonschema.ValidationError)
def json_validation_error(e):
return json_response("error", str(e), {})
This is my error handler
@app.validate('model', 'save')
def save_model():
This is my implementation:
{
"save": {
"type": "object",
"properties": {
"workspace": {"type": "object"},
"name": {"type": "string"},
"description": {"type": "string"},
"uri": {"type": "string"},
"type": {
"name": {"type": "string"},
}
},
"required": [ "workspace", "name", "description", "uri", "type"]
}
}
This is my model.json
file. It is validating the request except for the "type". How to apply validation for JSON request with nested object.
Solution
flask-expects-json package checks variables types on nested objects.
It work as a decorator on your route.
SCHEMA = {
"type": "object",
"properties": {
"workspace": {"type": "object"},
"name": {"type": "string"},
"description": {"type": "string"},
"uri": {"type": "string"},
"type": {
"type": "object",
"properties": {
"name": {"type": "string"},
}
}
},
"required": ["workspace", "name", "description", "uri", "type"]
}
@expects_json(SCHEMA)
def my_route(self, **kwargs):
pass
Answered By - AlexisG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.