Returning Meaningful HTTP Status Codes
HTTP status codes are essential for communication between clients and servers. They indicate whether a request was successful, failed, or needs further action. By returning meaningful status codes in your APIs, you make them easier to understand, debug, and integrate.
Table of Contents
Why Status Codes Matter
Imagine building an API that always returns 200 OK, regardless of what happened. The client would have no clue if the request was actually successful, if data was missing, or if there was a server error. Meaningful HTTP status codes provide that clarity and help clients respond correctly.
Common HTTP Status Codes
| Code | Meaning |
|---|---|
| 200 OK | The request was successful. |
| 201 Created | A resource was successfully created on the server. |
| 400 Bad Request | The client sent an invalid or malformed request. |
| 401 Unauthorized | Authentication is required. |
| 404 Not Found | The requested resource could not be found. |
| 500 Internal Server Error | A server-side error occurred. |
Examples in ASP.NET
In ASP.NET, you can return status codes using the built-in IActionResult return types. Here are some examples:
[HttpGet("{id:int}")]
public IActionResult GetItem(int id)
{
var item = _repository.Find(id);
if (item == null)
{
return NotFound(); // Returns 404
}
return Ok(item); // Returns 200
}
[HttpPost]
public IActionResult CreateItem(ItemDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Returns 400
}
var createdItem = _repository.Add(dto);
return CreatedAtAction(nameof(GetItem), new { id = createdItem.Id }, createdItem); // Returns 201
}Quick Reference Cheat Sheet
Here's a handy reference mapping real-world API scenarios to the most appropriate HTTP status codes:
| Scenario | Recommended Status |
|---|---|
| Fetching a list of items successfully | 200 OK |
| Creating a new user account | 201 Created |
| Client sends malformed JSON | 400 Bad Request |
| User tries to access without login | 401 Unauthorized |
| User requests a non-existent product | 404 Not Found |
| Server crashes during request | 500 Internal Server Error |
Status Code Decision Flow
To make it easier, here is a simplified decision flow diagram for selecting the right HTTP status code:
+---------------------+
| Did request succeed? |
+-----------+---------+
|
Yes ------+------ No
| |
+-----v----+ +----v------------------+
| 200 OK | | Is it the client's |
| (GET) | | fault (bad input)? |
+----------+ +----+------------------+
| Yes
+------v-------+
| 400 Bad Req |
+--------------+
|
No
|
+------------v--------------+
| Is authentication needed? |
+----+----------------------+
| Yes
+------v------+
| 401 Unauthorized |
+----------------+
|
No
|
+-----------v-------------+
| Resource exists? |
+----+--------------------+
| No
+------v------+
| 404 Not Found |
+--------------+
|
Yes
|
+------v------+
| 500 Server Error |
+-----------------+Best Practices
- Always return the correct status code for the situation.
- Provide descriptive error messages along with error codes for clarity.
- Use
201 Createdwhen creating resources instead of200 OK. - Avoid returning
500unless it is truly a server-side error. - Use
404 Not Foundfor missing resources, not200 OKwith an empty response.
Conclusion
Returning meaningful HTTP status codes is a small step that has a huge impact on the usability and maintainability of your APIs. By following best practices and using the right codes for the right situations, you help clients build robust applications that can interact seamlessly with your API.