Skip to content

Instantly share code, notes, and snippets.

@hirobert
Created January 13, 2016 20:38
Show Gist options
  • Select an option

  • Save hirobert/394981a661cbf78d442e to your computer and use it in GitHub Desktop.

Select an option

Save hirobert/394981a661cbf78d442e to your computer and use it in GitHub Desktop.
flask abort as json
from flask import abort, make_response, jsonify
abort(make_response(jsonify(message="Message goes here"), 400))
@tokland

tokland commented Jul 7, 2017

Copy link
Copy Markdown

From the docs, it wasn't obvious that flask.abort accepted also a flask.Response, very helpful, thx!

@xamgore

xamgore commented Nov 10, 2017

Copy link
Copy Markdown

Also you could do just

abort(jsonify(message="Message goes here"))

@CharlyJazz

Copy link
Copy Markdown

WWWWWWWWWWWWWWWWWWWWWOW

@lockie

lockie commented Apr 24, 2018

Copy link
Copy Markdown

<3

@danigosa

Copy link
Copy Markdown

Also you could do just

abort(jsonify(message="Message goes here"))

This is it 🚀

@pbuzulan

pbuzulan commented Aug 9, 2019

Copy link
Copy Markdown

@tamirOK in decorators you want to raise errors in some cases and not to return

@radzak

radzak commented Feb 3, 2020

Copy link
Copy Markdown

Notice that

abort(jsonify(message="Message goes here"))

returns 200 status code.

@zhanwenchen

zhanwenchen commented Mar 12, 2020

Copy link
Copy Markdown

THANK YOU THIS SAVED MY LIFE.

I was sooo frustrated. My solution is this:

abort(make_response(jsonify(errors=['Your input sucks', 'our service is down', 'Google is being slow suck it']), status, HEADERS))

@khaerulumam42

Copy link
Copy Markdown

thank you!

@pavelkomarov

pavelkomarov commented Jan 28, 2022

Copy link
Copy Markdown

This is goofy, because jsonify already returns a Response, but then you have to wrap it in another one just to set the status code. Why is abort this bad this many years on?

I'm doing abort(Response(f'{{["error":{str(ex)}}}\n'], status=400, content_type='application/json')) instead, because I regard it to be less of a hack. But really jsonify should have a parameter that allows you to set the status.

@stephenprn

Copy link
Copy Markdown

@pavelkomarov You can return specific status with jsonify by returning a tuple like this for example:

return jsonify({"error": "Unauthorized"}), 401

@caspii

caspii commented Mar 13, 2023

Copy link
Copy Markdown

If you have your API code in a blueprint, you can also do this I believe

@blueprint_api.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Sorry, board not found'}), 404)

The good thing here is that any other requests outside of the blueprint will continue to see the normal 404 page

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment