I am writing an API and expecting data in JSON. My function works well and stores data in SQLite as follows:
if request.method == 'POST':
if request.headers['Content-Type'] == 'application/json':
db = get_db()
data = json.loads(request.data)
row = (data['lat'], data['long'], data['address'], data['name'])
db.execute('INSERT INTO places (lat, long, address, name) values (?, ?, ?, ?)', row)
db.commit()
resp = Response(status=200, mimetype='application/json')
return resp
If someone sends a POST with incorrect JSON fields (missing lat, long, address or name), then an error is thrown by Flask.
What’s the best way to handle this?
I tried doing:
if not 'lat' in data or if not 'long' in data or ....
But data is just a string and not a dictionary. So I have two questions:
- How are the filed being references as if its a dictionary above (
data['lat']…)? - What is an appropriate way to handle this error?
The moment you load data from JSON with
data = json.loads(request.data)you have a python structure.If at that time it is not a dictionary, then whatever the request sent you did not hold the correct JSON structure (could be a list, for example).
I’d use a
try/execeptin this case:An exception will be raised if
request.datais not valid JSON, or ifdatais not a dictionary with the correct keys. The three exceptions listed are what would be raised by the various error modes that are possible: