Return HTTP status code 201 in flask
-
27-10-2019 - |
Pergunta
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?
Solução
You can read about it here.
return render_template('page.html'), 201
Outras dicas
You can use Response to return any http status code.
> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')
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.
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
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")
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/