Validate API json payload

937 ワード

I found openstack use jsonschema to validate API. Voluptuous might be another option for input validation.
Jsonschema is more popular than voluptuous. And we can find many examples about jsonschema
How to use json-schema?
schema = {
    "type": "object",
    "properties" : {
        "price" : {"type": "number"},
        "name" : {"type": “string"},
    },
}
validate({"name": "bran", "price": 20}, schema)      passed
validate({"name": "bran", "price": "noprice"}, schema)   will raise ValidationError: 'noprice' is not of type 'number'

Json-Schema allow us specify properties type to number, string, array, object… You can understand more about json schema from this link: https://spacetelescope.github.io/understanding-json-schema/reference/object.html