[python] 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?

This question is related to python flask httpresponse http-status-code-415

The answer is


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.


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

You can do

result = {'a': 'b'}
return jsonify(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


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/


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

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.


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

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


You can use Response to return any http status code.

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to flask

Flask at first run: Do not use the development server in a production environment Flask - Calling python function on button OnClick event python-How to set global variables in Flask? In Flask, What is request.args and how is it used? How to print from Flask @app.route to python console What does "app.run(host='0.0.0.0') " mean in Flask Making an asynchronous task in Flask Flask ImportError: No Module Named Flask can you add HTTPS functionality to a python flask web server? How to get http headers in flask?

Examples related to httpresponse

Return content with IHttpActionResult for non-OK response Why should I use IHttpActionResult instead of HttpResponseMessage? download csv file from web api in angular js Proper way to return JSON using node or Express Writing MemoryStream to Response Object Returning http status code from Web Api controller Difference between Pragma and Cache-Control headers? How to Use Content-disposition for force a file to download to the hard drive? Return HTTP status code 201 in flask How to get HTTP Response Code using Selenium WebDriver

Examples related to http-status-code-415

How can I get the status code from an http error in Axios? Curl to return http status code along with the response Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details How to deal with http status codes other than 200 in Angular 2 HTTP 415 unsupported media type error when calling Web API 2 endpoint AngularJS POST Fails: Response for preflight has invalid HTTP status code 404 Laravel - Return json along with http status code Swift Alamofire: How to get the HTTP response status code Spring Boot Rest Controller how to return different HTTP status codes? Http 415 Unsupported Media type error with JSON