213

We're using Flask for one of our API's and I was just wondering if anyone knew how to return a HTTP response 201?

For errors such as 404 we can call:

from flask import abort
abort(404)

But for 201 I get

LookupError: no exception for 201

Do I need to create my own exception like this in the docs?

2
  • 35
    return '', 201
    – Luc
    May 11, 2016 at 8:13
  • 1
    This, as 201 is not an error. It is a success status. Jun 8, 2021 at 21:05

12 Answers 12

242

You can use Response to return any http status code.

> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')
2
  • 2
    You can rewrite this as return {'a':'b'}, 201, {'Content-Type': 'application/json'}, or simply as return {'a': 'b'}, 201 Jun 16 at 8:34
  • 2
    @MasoodKhaari's approach is actually correct since it returns valid JSON - it looks like {'a':'b'} gets automatically converted to {"a":"b"}. The double quotes are correct JSON. The original answer actually returns single quotes.
    – antun
    Aug 25 at 21:42
196

You can read about it here.

return render_template('page.html'), 201
2
  • 20
    This requires page.html... It won't work by itself. Nov 14, 2018 at 21:57
  • For me this type of error handling worked (behind IIS) only if InvalidUsage was a child of werkzeug.exceptions.HTTPException, not a general Exception Jun 15, 2020 at 9:36
49

You can do

result = {'a': 'b'}
return result, 201

if you want to return a JSON data in the response along with the error code You can read about responses here and here for make_response API details

0
32

As lacks suggested send status code in return statement and if you are storing it in some variable like

notfound = 404
invalid = 403
ok = 200

and using

return xyz, notfound

than time make sure its type is int not str. as I faced this small issue also here is list of status code followed globally http://www.w3.org/Protocols/HTTP/HTRESP.html

Hope it helps.

1
  • 2
    Good way, but better to access them as a module like status.NOT_FOUND
    – roshnet
    May 26, 2021 at 21:04
15

In your flask code, you should ideally specify the MIME type as often as possible, as well:

return html_page_str, 200, {'ContentType':'text/html'}

return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

...etc

8

Ripping off Luc's comment here, but to return a blank response, like a 201 the simplest option is to use the following return in your route.

return "", 201

So for example:

    @app.route('/database', methods=["PUT"])
    def database():
        update_database(request)
        return "", 201
7

you can also use flask_api for sending response

from flask_api import status

@app.route('/your-api/')
def empty_view(self):
    content = {'your content here'}
    return content, status.HTTP_201_CREATED

you can find reference here http://www.flaskapi.org/api-guide/status-codes/

1
  • 2
    upvoted for using a constant instead of a magic number Jun 27, 2022 at 11:12
4

In my case I had to combine the above in order to make it work

return Response(json.dumps({'Error': 'Error in payload'}), 
status=422, 
mimetype="application/json")
2

Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. For example if it was creating a user account you would do something like:

return {"data": {"username": "test","id":"fdsf345"}}, 201

Note the postfixed number is the status code returned.

Alternatively, you may want to send a message to the client such as:

return {"msg": "Created Successfully"}, 201
2

for error 404 you can

def post():
    #either pass or get error 
    post = Model.query.get_or_404()
    return jsonify(post.to_json())

for 201 success

def new_post():
    post = Model.from_json(request.json)
    return jsonify(post.to_json()), 201, \
      {'Location': url_for('api.get_post', id=post.id, _external=True)}
2

You just need to add your status code after your returning data like this:

from flask import Flask

app = Flask(__name__)
@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!',201
if __name__ == '__main__':
    app.run()

It's a basic flask project. After starting it and you will find that when we request http://127.0.0.1:5000/ you will get a status 201 from web broswer console.

1
  • 2
    Welcome to SO. This is a ten year old question that has been answered already! :o)
    – ingh.am
    Dec 20, 2021 at 12:07
1

So, if you are using flask_restful Package for API's returning 201 would becomes like

def bla(*args, **kwargs):
    ...
    return data, 201

where data should be any hashable/ JsonSerialiable value, like dict, string.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.