I am creating an API using Flask and Flask-RESTful. I wish to parse the body of an incoming request using flask_restful.reqparse.RequestParser(). Upon receiving an incorrect JSON, I would like to return a 400 Bad Request response. However, my application is instead returning a 500 Internal Server Error response. I thought the RequestParser() was supposed to handle these responses automatically? Can anyone explain what is going wrong?
Below is the code for the API Resource
from flask_restful import Resource, reqparse
class Foo(Resource):
parser = reqparse.RequestParser()
parser.add_argument("foo",
type=int,
required=True,
action='append',
help="Request body must contain a 'foo' key which comprises a list of IDs, e.g. {'foo': [44, 3213, 532, 4312]}"
)
def get(self):
data = self.parser.parse_args(strict=True)
return {'bar': data['foo']}
When I send a GET request to the API with the body {"err": [3, 4, 1]} I receive the following 500 Internal Server Error response:
{"message": "Internal Server Error"}
and not the message I specified in the help parameter. In my logs I also get the following error message:
KeyError: "'foo'"
I know I could wrap the data = self.parser.parse_args(strict=True) in a try/except KeyError clause and handle the incorrect JSON myself, but I thought that Flask-RESTful would do that for me? What else could I try?