Reputation: 736
I have a complex payload being used in the api as below. Is there a way to validate the below keys in the sample payload exists (request data given in POST or PUT)
{
"adduser": {
"usergroup": [
{
"username": "john",
"userid": "kk8989",
"user_contact": 9343454567,
"manager_name": "sam",
"manager_contact": 9343454597,
"env": "dev",
"partner": {
"name": "macy",
"address": "radom address",
"assets": [
"iphone",
"tesla"
],
"profile": {
"linkedin": "XXXX",
"facebook": "XXXX"
},
"children": [
{
"name": "tim",
"address": "XXXX"
},
{
"name": "tim",
"address": "XXXX"
},
{
"name": "tim",
"address": "XXXX"
}
]
}
}
]
}
}
How to validate the above repayload before using it in the application.
Upvotes: 0
Views: 2805
Reputation: 46
You can try to use attr and cattr packages:
import attr, cattr
@attr.s
class Response:
name = attr.ib()
val = attr.ib(type=int, default=5)
d = cattr.structure({'name': 'some name'}, Response)
print('-->', d)
If you remove default value from val attribute, you'll get a TypeError exception. So, it's up to you how to handle absence of keys. Read packages docs anyway.
Upvotes: 1
Reputation: 506
The input json is treated just like a dict in python, to validate for keys, or values, you can simply work with the dictionary. E.g. to check if it contains 'school' key u can use if 'school' in json_dict:
@app.route('/', methods=["PUT", "POST"])
def new():
json_dict = request.get_json(force=True)
if 'school' not in json_dict:
return 'Error, school not found'
You can also wrap the request.get_json call in a try except for better exception handling.
You can use jsonschema
library to validate against your json schema/model.
check out this post here describing the validate() function from jsonschema
.
http://code.activestate.com/recipes/579135-validate-data-easily-with-json-schema/
Upvotes: 0