Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API in Flask--returns JSON but HTML exceptions break my JSON client

exceptions returned in HTML break my JSON client. I want to jsonify this output.

More detail: i have a view function which an endpoint of this api app.

As you can see, this function returns the result in json.

@app.route('/route1')
def api_route1():
    if user_id in request.args: 
        k1 = request.args['user_id']
        return flask.jsonify(recs=some_function(k1))
    else:
        return "no valid user_id supplied"

The problem, unhandled exception are in HTML, e.g.,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 
    Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>TypeError: 'NoneType' object is not iterable // Werkzeug Debugger</title>
        <link rel="stylesheet" 
            href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css" 
            type="text/css">

This breaks my json client. The HTML format is clearly a default, but i don't know how to opt out of it and specify jsonified exceptions (and ideally jsonify anything returned even headers).

I suspect what i need is somewhere in the excellent Flask documentation, but i can't find it.

like image 211
doug Avatar asked Dec 08 '12 02:12

doug


People also ask

What is Flask Jsonify?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.


2 Answers

You should define HTTP error handlers in flask.

A simple JSON returing 404 handler might look something like this:

@app.errorhandler(404)
def page_not_found(e):
    return flask.jsonify(error=404, text=str(e)), 404

With this you will be able to check for data.error on the client and if it exists you can get the error text with data.text (the error passed as e is werkzeug.exceptions.NotFound whose string representation is "404: Not Found").

like image 112
computmaxer Avatar answered Sep 19 '22 09:09

computmaxer


Making the traceback available to the JSON client has the potential to disclose sensitive information.

My advice is:

  • turn debug off
  • install a log aggregation tool like sentry
  • make the error 500 page for this application return a generic error in json format

The 500 page could look like:

{ "error": "500 - internal server error" }
like image 30
Paulo Scardine Avatar answered Sep 18 '22 09:09

Paulo Scardine