httphttp-response-codes

Why and how HTTP responses' status code matter?


Genuine question; there are so many HTTP status codes and people always motivate for you to use the correct one in a certain situation.

Except for the common ones (200, 404, and 500), does it really matter what HTTP status code I send back to the user?

Does the browser does something different with each status code?


Solution

  • In many cases: no. As long as you use the correct class of errors (4xx, 5xx) many things will just work.

    The purpose of using more specific HTTP status codes is two fold:

    1. It can be helpful documentation for a programmer running into them.
    2. It allows a generic client to handle results in a generic way.

    Some examples for #2:

    A good client can make these types of decisions completely independent of your API. It knows how to behave because these are agreed upon standards.

    But if you don't make use of clients that can handle any of these advanced features, then it is less important to use them.

    All of these status codes are more or less designed with this idea in mind; perhaps it can allow clients to automatically resolve an error, perhaps it will immediately understand whether a cache should be marked stale, or perhaps it can render good default feedback to an end-user.

    However, most APIs and clients will only make use of a few of these features. So my general advice would be:

    1. It doesn't really hurt to use the right status code
    2. Making yourself familiar with status codes can help you design your API in a way to use well-designed common features in a way that is similar to how someone else might build it, instead of say: reinventing the wheel for your specific use-case.
    3. Don't sweat it if you don't know if you (for example) should return a 400, 403, 409, 422 and you can't see a practical benefit to each.

    If you want to read more, see what one of the major authors of recent HTTP standards has to say about this: https://www.mnot.net/blog/2017/05/11/status_codes

    I also wrote a series of blog post about each status along with real-world uses for each: https://evertpot.com/http/