R.Roshan
R.Roshan

Reputation: 199

Flask restful initial json validation for the post request

I have flask restful application. I tried to pass invalid json and my server throw html tags to user.

How can throw nice error message to user saying json not valid.? POST method

class MyView(Resource):

    def post(self):
        try:
            signup_data = request.get_json(force=True)
            country_code = signup_data['country_code']

Data passed (invalid json)

{
    "country_code": "hello",
    "country_code": "hello"
}

Error message

File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line
1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)   
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py",
line 484, in wrapper
return self.make_response(data, code, headers=headers)   
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py",
line 513, in make_response
resp = self.representations[mediatype](data, *args, **kwargs)   
File "/usr/local/lib/python2.7/dist-packages/flask_restful/representations/json.py",
line 21, in output_json
dumped = dumps(data, **settings) + "\n"   
File "/usr/lib/python2.7/json/__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)   File "/usr/lib/python2.7/json/encoder.py", line 209, in encode
chunks = list(chunks)   
File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode
o = _default(o)   
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable") 
TypeError: <Response 29 bytes [200 OK]> is not JSON serializable

output to user

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"> TypeError: <Response 29 bytes [200 OK]> is not JSON serializable // Werkzeug Debugger

Upvotes: 1

Views: 3025

Answers (1)

dvnguyen
dvnguyen

Reputation: 3022

You can try - except the line reading json input, catch the TypeError and throw a nice error message there:

try:
    signup_data = request.get_json(force=True)
except TypeError:
    return jsonify(message="Invalid json input"), 400

Use from flask import jsonify to import jsonify

Upvotes: 1

Related Questions