ASP.NET Core Web API Interview Question #20
When should a Web API return 404 Not Found?
Web API & REST Fundamentals, Controllers, HTTP Methods & Status Codes Junior Beginner
Quick Interview Answer
404 Not Found indicates that the requested resource or route cannot be found. For a resource endpoint, return 404 when the identifier is valid in form but no matching accessible resource exists.
Detailed Explanation
404 Not Found indicates that the requested resource or route cannot be found. For a resource endpoint, return 404 when the identifier is valid in form but no matching accessible resource exists.
Do not return 200 with null merely to indicate a missing resource unless that behavior is an intentional and documented contract.
Code Example
[HttpGet("{id:int}")]
public async Task<IActionResult> Get(int id)
{
var item = await _service.GetAsync(id);
return item == null
? NotFound()
: Ok(item);
}