Technology

The HTTP 204 (No Content)

HTTP 204 No Content

Last week, we only had 3 working days since Monday was National Heroes Day and Friday was Eidul Adha. I didn’t have any out of town plans as I wanted to just review for my GRE exam. But alas, I decided to instead build a PHP Package for the Have I Been Pwned API.

If your email is found here, then your account might have been compromised. I’ve read this article and felt that I’ve heard about the name Troy Hunt already somewhere. Then I realized it was his article on API versioning that I was able to read a few months back.

I immediately read the API documentation and went on building and designing my PHP package for this. I thought one of the API endpoints was not working so I immediately contacted Troy via Twitter. Amazingly, he replies fast! He said that it’s working fine on his end. But I told him it was the API endpoint that wasn’t returning a Body Response. We had a few exchanges; I misunderstood him and misread the documentation.

When a password is found in the Pwned Passwords repository, the API will respond with HTTP 200. When no match is found, the response code is HTTP 404. There is no body returned with either response. (Pwned Passwords API Documentation)

The API endpoint for pawned passwords actually does not return any body response. The client should only expect either a 200 OK or 404 Not Found header code. I had to do some tweaks on my base class. It was built to always expect a body response when receiving 200 OK. I did research about 200 OK and here’s what I got:

Aside from responses to CONNECT, a 200 response always has a payload, though an origin server MAY generate a payload body of zero length. If no payload is desired, an origin server ought to send 204 (No Content) instead.  (rfc7231#section-6.3.1)

So, does that mean that the API should be using 204 No Content instead? Well, maybe, but not necessarily. There could’ve been several factors why the author did not use it. What we, as API consumers, can do right now is to adjust and make our clients as robust and loosely coupled as possible. I am also a backend developer so I’d understand how difficult it is to balance modifications in the backend in vis-a-vis to your consumers.

I’m also pleased to present that I’ve already released github.com/ridvanbaluyos/haveibeenpwned at packagist.org as v0.1. Some Unit Tests are still failing but this is mainly due to setup configuration in Scrutinizer CI. Let me know if you encounter issues or if you have any further suggestions!

Further Readings:
http://blog.ploeh.dk/2013/04/30/rest-lesson-learned-avoid-204-responses/
https://github.com/julienschmidt/httprouter/issues/156

Leave a Reply

Your email address will not be published. Required fields are marked *