Search code examples
pythontornado

Return a pure json error in Tornado


def get(self):
    self.set_status(400, '["reason"]')
    self.finish()
    return

When you get this response you can get response.error.message which has the message HTTP 400: ["reason"]. But what if you wanted a pure json response as an error. What would be the best way to get that?


Solution

  • The second argument to set_status() is the "reason" string, i.e. the "Not Found" in HTTP/1.1 404 Not Found. It's human-readable, not machine readable, and many HTTP clients simply discard it. You should only use this parameter when you are sending a status code that is not found in the standard list.

    Instead, when you want to send a JSON message along with an error, call self.set_status(code), and then write your output as usual into the body:

    self.set_status(400)
    self.finish({"reason": reason})