When to use HTTP Status Codes (and when not to)
Mastering HTTP status codes is essential for building robust APIs and ensuring clear client-server communication.
When building an API or web application, understanding HTTP status codes is crucial. These codes form the backbone of client-server communication, helping you convey the outcome of requests sent to your application's resources. A common pitfall during technical interviews is mishandling these codes, leading to confusion not only in communication with clients but also potentially causing functional issues in production. Let's dive into how to use these codes effectively, particularly when to leverage them and when they could mislead users or developers.
Core HTTP Status Codes and Their Use Cases
Among the multitude of HTTP status codes, the most commonly encountered ones are categorized by their first digit:
- 1xx (Informational): Not widely used in practice but indicates a provisional response.
- 2xx (Success): Indicates successful requests. Codes like
200 OK(successful GET) and201 Created(successful POST) are essential for indicating that the request was processed as intended. - 3xx (Redirection): Indicates further action needs to be taken to complete the request.
- 4xx (Client Error): Indicates that the request contains bad syntax or cannot be fulfilled, e.g.,
404 Not Found,403 Forbidden, and400 Bad Request. - 5xx (Server Error): Indicates that the server failed to fulfill a valid request, such as
500 Internal Server Erroror503 Service Unavailable.
Using these codes correctly not only informs users of what went wrong but also helps developers troubleshoot issues effectively.
Choosing Between 400 and 500 Status Codes
One tension candidates often face in interviews is deciding when to use a 400 Bad Request versus a 500 Internal Server Error. It’s critical to get this right.
- Use
400 Bad Requestwhen the client sends an invalid request that the server cannot process due to client-side issues. For example, if a user submits a form with invalid data. - Use
500 Internal Server Errorwhen something goes wrong on the server-side that the client hasn’t caused, making it a server issue beyond a client’s control.
This distinction informs the client whether to correct their input or wait for server issues to be resolved, which is essential for providing a good user experience. Let’s take a look at a minimal code example of how these might be implemented in Express.js, a common Node.js framework:
app.post('/submit', (req, res) => {
const { data } = req.body;
if (!data || typeof data !== 'string') {
return res.status(400).json({ error: 'Invalid input provided.' }); // Bad Request
}
// Process valid request logic here...
// If an error occurs internally:
// return res.status(500).json({ error: 'Internal server error.' }); // Internal Server Error
});
This code snippet checks if the incoming data is valid before proceeding. If it’s not, it sends a 400 status code indicating a client error. This kind of validation is essential.
Interview Traps
Candidates often overlook the importance of status codes during interviews. Here are common pitfalls and things interviewers may push on:
- Misusing 500 for Client Errors: Confusing server-side issues with client-side mistakes can lead to erroneous debugging processes. Know when to identify the source of the error.
- Vague Documentation: Expect interviews to stress how you might document your API responses. Clear documentation will help consume APIs better.
- Assuming Default Behavior in Frameworks: When using tools like Express, understand how they manage status responses on errors, and ensure you override the defaults when necessary.
- Overlooking Specific Codes: Candidates might not realize the importance of using more specific codes, like
403 Forbiddenfor permission errors instead of a generic404 Not Found.
A Worked Example
Let’s analyze a potential interview scenario:
Scenario: You develop an API endpoint for users to fetch their profiles. If a user requests a profile that doesn’t exist, how do you respond?
- Identify the Request: When a user requests a profile that cannot be found.
- Select the Right Status Code:
- A
404 Not Foundresponse is appropriate here because it clearly states that the resource (profile) doesn’t exist.
- A
- Implement:
app.get('/user/:id', (req, res) => {
const userProfile = findUserById(req.params.id);
if (!userProfile) {
return res.status(404).json({ error: 'User not found.' });
}
return res.status(200).json(userProfile);
});
This code clearly distinguishes between found and not found cases, facilitating better troubleshooting and user feedback.
On the Job
In production, mismanaged HTTP status codes can lead to significant problems. For instance, if a client receives a 500 error erroneously attributed to their request, they may waste time attempting to fix what isn’t broken. Conversely, not adhering to proper codes could result in unexpected behavior in client applications, especially those built on top of your API, which expect a specific set of responses to handle errors robustly.
Conclusion
In short, knowing when to use the right HTTP status code is as crucial as understanding the status codes themselves. It empowers users, creates transparency, and facilitates quicker debugging. As you prepare for your interviews and advance in your role, keep these distinctions in mind and leverage them to build better APIs.
References
Ready to practice HTTP Status Codes?
Answer real questions, get instant feedback, and watch your skill score climb — free. Practice is in English, like real tech interviews.
Try one 👇
↑ Go ahead — pick an answer. This is Skillpato.