Search code examples
c#getapi-designhttp-status-codes

HTTP Status Codes - 404/NotFound vs 204/NoContent vs 200/Ok


I have Widget entities that belong to Company entities. There is a one-to-many relationship between Companies and Widgets.

Here's my first pass at the Get method:

[Route("MyApi/Companies/{companyId}/WidgetAdministration/[controller]")]
[HttpGet]
public async Task<ActionResult<List<WidgetDTO>>> GetWidgets([FromRoute] int companyId)
{
    // get company
    var company = await _xyvidContext.Companies
        .Where(c => c.CompanyId == companyId)
        .AsNoTracking()
        .Include(c => c.Widgets)
        .FirstOrDefaultAsync();

    if (company == null)
    {
        return NotFound();
    }

    // get corresponding Widgets
    List<WidgetDTO> widgetDtos = company.Widgets
        .AsQueryable()
        .ProjectTo<WidgetDTO>(_mapper.ConfigurationProvider)
        .ToList();

    if (widgetDtos == null)
    {
        return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError);
    }
    else if (widgetDtos.Count == 0)
    {
        return NoContent();
    }
    else
    {
        return Ok(widgetDtos);
    }
}

It is obvious that if the Company is Not Found, whether it was soft-deleted or never existed, I should return a 404/NotFound, Correct ?

If I request to see all Widgets belonging to Company 1, but Company 1 has not Widgets, what should I return?

404/NotFound - No Widgets were found.

204/NoContent - No Widgets were found, so there is No Content to return

200/Ok with Empty Array - No Errors occurred, but what we found was an empty array, so just return that.


Solution

  • Yes, a 404 would be the correct return code for a non-existent company, because if you were to return a success code, the developer using your API would have to add extra checks for that, or you would have to come up with fake data to fulfill the request. On top of that, most languages have easy ways to check for and handle error status codes.

    As for the widgets, because it's an array, this is really up to you. Although, 4xx codes indicate an error. Just because of that, I would personally recommend using either 204 or 200 as 2xx indicates a success. A 404 would be more appropriate if they try to retrieve a list of widgets for a company that doesn't exist.

    Really what it comes down to is consistency and simplicity. Most APIs will always just use code 200 and return an empty array in this case, because then the developer using the API can (usually) use the same or similar code to handle requests whether the array is empty or not. If you return a different status code (204) rather than just an empty array, the developer using your API will have to add an extra check for that and will more than likely create and return an empty array anyway. Plus, it gets rid of an extra couple lines in your posted code as well.