How does one know when to use if statements and status codes?


#1

Question

How does one know when to use if statements and status codes?

Answer

It is recommended to keep checks at every request even if it is a get request to the root route /, this is because we want the user of the API to know that either there is no data available for the request, that there was something wrong, or that there was a successful result and that they will be able to see it.

The same way we want to incorporate status codes, even if it is the most necessary ones only like 404 (not found), 403(forbidden), or 501(bad gateway) that would come for an unexisting route.

So to know where to start, we need to think about what kind of data the route will return and if it is related to something that a user has created or if it should already exist in the server, if it is related to a user or if we cannot be sure there is data to return we should implement checks as if statements or switch cases (if fitting) and applying status codes in our responses.


FAQ: Code Challenges - Code Challenge