ingh.am
ingh.am

Reputation: 26742

Return HTTP status code 201 in flask

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?

Upvotes: 223

Views: 350281

Answers (13)

Sadique Khan
Sadique Khan

Reputation: 320

Use something like this as per latest flask version 3.0.2

return render_template('main.html', status=201, data=data)#where main.html is template name and data is variables to be passed to the template

Upvotes: 0

Kishan K
Kishan K

Reputation: 811

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

Upvotes: 53

Xie Yuchen
Xie Yuchen

Reputation: 116

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.

Upvotes: 2

Josie Koay
Josie Koay

Reputation: 831

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)}

Upvotes: 2

Matt Copperwaite
Matt Copperwaite

Reputation: 340

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

Upvotes: 14

Iacks
Iacks

Reputation: 3845

You can read about it here.

return render_template('page.html'), 201

Upvotes: 204

Croc
Croc

Reputation: 838

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

Upvotes: 2

Deepak Sharma
Deepak Sharma

Reputation: 1739

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.

Upvotes: 1

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

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/

Upvotes: 7

Cheetara
Cheetara

Reputation: 175

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")

Upvotes: 5

Ben Wheeler
Ben Wheeler

Reputation: 7344

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

Upvotes: 17

Yasir
Yasir

Reputation: 4767

You can use Response to return any http status code.

> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')

Upvotes: 258

Harsh Daftary
Harsh Daftary

Reputation: 2653

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.

Upvotes: 34

Related Questions