Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return NotFound status code or empty list with status code 200 when search action finds no elements in asp.net web api call?

A mvc web api call like GetEmployees searches for a list of employee objects but finds none. This is not an error condition as it is acceptable in the business context that the list can be empty.

The search did not fail, it just didn't find anything.

What is the best way to form the response? Should I

  1. return a response message with http status code of HttpStatusCode.NotFound, or
  2. return status code 200 and return an empty list, or
  3. something else?
like image 216
Johan Malherbe Avatar asked Oct 16 '25 15:10

Johan Malherbe


1 Answers

By returning a 404 you say the requested resource isn't available, like GET /Emplyees/42 where an employee with that ID doesn't exist.

Your employee collection does exist, it's just empty, so 404 would be inappropriate.

See RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1:

The server has not found anything matching the Request-URI.

Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content:

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

REST: Mapping 404 HTTP Status codes:

If the URL is supposed to return a [...] representation then a 404 should be returned if the code does not exist. If the URL returns a [...] result then it shouldn't return a 404.

So you could consider returning 204 No Content, or a 200 with either an empty body or a response indicating an empty collection.

like image 144
CodeCaster Avatar answered Oct 19 '25 13:10

CodeCaster