Flask is an amazing framework for building web application in Python. It’s main features are easy to use, very small learning curve, it has everything included that you need (or it can be easily extended) and it just gets out of your way of development.
It offers few simple ways to return data in format that we want: HTML, JSON, XML and others.
204 No Content response
If we imagine that we have a view for deleting user
1 2 3 |
@app.route('/users/<int:id>', methods=['DELETE']) def delete_user(id): ... |
There has been many discussion what a DELETE method should return. My opinion is that 204 No Content is must suitable solution. We could also return 200, but I really don’t see any additional information that could be returned that we could use. If it’s deleted, it’s deleted.
204 No Content status is exactly what we need. Because it does not have body, just the status 204. How can be use this with Flask? Let’s complete the method
1 2 3 4 5 |
@app.route('/users/<int:id>', methods=['DELETE']) def delete_user(id): method_to_delete_user_by_id(id) return '', 204 ... |
It’s just one line of the code return '', 204'
. This will return the empty content with status 204. Pretty easy and amazing.
If we don’t want to include and remember the 204 status code, we can also use constants.
1 2 3 4 5 6 |
@app.route('/users/<int:id>', methods=['DELETE']) def delete_user(id): method_to_delete_user_by_id(id) return '', httplib.NO_CONTENT # for python 2.x return '', http.HTTPStatus.NO_CONTENT # for python 3.x ... |
204 No Content and Content Type
If you have this view as part of the API, you will notice that response content type is actually text/html; charset=utf-8
. This is OK for normal page, but not for API (where we would probably prefer application/json
).
We could easy write a simple helper method
1 2 3 4 5 |
def jsonify_no_content(): response = make_response('', 204) response.mimetype = current_app.config['JSONIFY_MIMETYPE'] return response |
We follow similar naming as flask’s jsonify method. Then we can just simple use it.
1 2 3 4 5 |
@app.route('/users/<int:id>', methods=['DELETE']) def delete_user(id): method_to_delete_user_by_id(id) return jsonify_no_content() ... |
and we will get 204 No Content status code with application/json
content type.