Web traffic follows a fairly standard flow. Request to Response. Someone makes a request to a server (e.g., your mobile phone makes a request to Twitter’s server), and the server then processes that request and sends a response. All responses include a status code. The most common status code people see is 404 (and websites have gotten pretty clever with their responses). Status codes belong to one of five groups:
- 100 – 199 = Information
- 200 – 299 = Success
- 300 – 399 = Redirection
- 400 – 499 = Client Error
- 500 – 599 = Server Error
You may see these referred to as 1xx, 2xx, 3xx, etc. to denote the ranges. A server error (5xx) may happen when an application says “Hey, the code crashed and I cannot recover. Return a 500 (Internal Server Error).“
User-facing web apps typically have a custom error page. Remember those clever 404 pages linked above? That’s simply a custom error page on the 404 status code. The flow goes like:
- The application code raises an error.
- The application then creates a response with a 500 status code.
- The server the is running the application intercepts the 500 response, and instead returns a “more user-friendly” error page (such as these).
- The user actually gets back a valid HTML page informing them an error occurred.
- Plot Twist: The status code for the HTML error page is actually 200 (“success”). Although there was an error, the server intercepted the “error” response and returned a friendly HTML page. Because that HTML page was returned successfully, the status code is 200.
The trick with web APIs
A RESTful web API is expected to use meaningful error codes. In other words, instead of sending a friendly response of “Whoops, some error occurred”, an API should use a status code to indicate what happened. Remember that APIs are meant to be called programmatically, and a friendly error page only obfuscates what happened. For example,
- [GET] api/users/some-non-existent-user should return a 404 (not found)
- [POST] api/users/some-existing-user should return a 409 (conflict)
Check out the fantastic list over at https://www.restapitutorial.com/httpstatuscodes.html for more details.