Flask return 204 No Content response

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

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

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.

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

We follow similar naming as flask’s jsonify method. Then we can just simple use it.

and we will get 204 No Content status code with application/json content type.

Hi, I'm Erol
Senior Fullstack Developer

I'm available for hire. So if you need help, send me an email.