jdm
jdm

Reputation: 10070

Plain (non-HTML) error pages in REST api

I'm writing a simple REST service with Flask. When an exception occurs in my code, I get a nice error message and an interactive debugger in my browser. However, if I call the service from the command line (e.g. with curl), or in my unit tests, and something fails, I still get the formatted (HTML) error message. I remember that I sometimes got a plain text message instead (basically just the Python error + traceback), and I don't know how Flask decides to serve plain text or HTML.

How do I make it so that Flask returns plain (non-interactive, non-HTML) error messages when accessed without a browser?

Upvotes: 5

Views: 1210

Answers (2)

Audrius Kažukauskas
Audrius Kažukauskas

Reputation: 13543

To handle exceptions in production mode, register error handler for 500 status code. From it you can return anything you want. Here's an example that returns exception itself as plain text:

@app.errorhandler(500)
def error_500(exception):
    return str(exception), 500, {'Content-Type': 'text/plain'}

If it's API you're writing, returning JSON encoded data as application/json may be more appropriate.

Upvotes: 7

Burhan Khalid
Burhan Khalid

Reputation: 174622

Set app.debug = False to turn off the fancy error reporting. The documentation has more on debug mode.

Upvotes: 5

Related Questions