Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return HTTP status code 201 in flask

People also ask

How do I return a flask status code?

To send JSON and status code with a Python Flask response, we can return a tuple with the response body and the status code in our view. to add the login view with the response returned. We return the body with jsonify(data) and we return the status code by putting 200 in the same tuple.

What is a 201 response code?

The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource.

Which method of rest will give status code 201 in response?

HTTP Status 201 indicates that as a result of HTTP POST request, one or more new resources have been successfully created on the server.


You can use Response to return any http status code.

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

You can read about it here.

return render_template('page.html'), 201

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.


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


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