Isaac.

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.

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

CodeMeaning
200 OKThe request was successful.
201 CreatedA resource was successfully created on the server.
400 Bad RequestThe client sent an invalid or malformed request.
401 UnauthorizedAuthentication is required.
404 Not FoundThe requested resource could not be found.
500 Internal Server ErrorA 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:

ScenarioRecommended Status
Fetching a list of items successfully200 OK
Creating a new user account201 Created
Client sends malformed JSON400 Bad Request
User tries to access without login401 Unauthorized
User requests a non-existent product404 Not Found
Server crashes during request500 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 Created when creating resources instead of 200 OK.
  • Avoid returning 500 unless it is truly a server-side error.
  • Use 404 Not Found for missing resources, not 200 OK with 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.