darksky
darksky

Reputation: 21069

Handling POST JSON Error in Flask

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:

  1. How are the filed being references as if its a dictionary above (data['lat']...)?
  2. What is an appropriate way to handle this error?

Upvotes: 3

Views: 7461

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124928

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 / execept in this case:

try:
    data = json.loads(request.data)
    row = (data['lat'], data['long'], data['address'], data['name'])
except (ValueError, KeyError, TypeError):
    # Not valid information, bail out and return an error
    return SomeErrorResponse

An exception will be raised if request.data is not valid JSON, or if data is not a dictionary with the correct keys. The three exceptions listed are what would be raised by the various error modes that are possible:

>>> import json
>>> json.loads('nonsense')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 338, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>> 'ouea'['abc']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not str
>>> [0]['oue']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> {}['oue']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'oue'

Upvotes: 10

Related Questions