Rest service returns 404

2019-09-17 20:48发布

问题:

What is the best practice in return codes if a call to a rest service executes a database query, no results are found and it returns.

Should this be a 404 or a 200 with a message stating no records?

The URL has resolved correctly and no server error has occurred just that there are no records returned.

EDIT: Example url is:

http://localhost/app/pr_xyz/1234

Used to retrieve a list of xyz that belong to the existing user 1234. The user id 1234 has already been retrieved and is known to exist in the database. This URL (pr_xyz) is just to retrieve a list of xyz that belong to that user.

The relationship is 1 user to 0 or many xyz.

In this case the existing user has no xyz. Should this be a 404 or 200 with meaningful message.

Also I have no control over the URL.

回答1:

Agree with @Satya, it should be a 200, but we can arrive at the answer by working backwards.

So, we start with the full list of HTTP status codes.. Start from the bottom.

  • Is it a server error? No? Then it's not a 5xx
  • Is it a client error? Maybe? Perhaps it's not a 4xx
  • It's obviously not a redirect, so it's not a 3xx.
  • Is it a successful call? Perhaps.
  • Are you returning a provisional response? No, it's not a 1xx either.

So by process of elimination, which are looking at the 2xx codes. Exactly which would be a good fit depends on the semantics of your application.

Since, this is not a DELETE call, then I probably wouldn't use 204 No Content, which is probably the only good alternative. It's not that there's no content.

There is content: "0 results found". Google doesn't show you a blank page when there are no search results.

So we arrive at 200, as well as returning a meaningful body. If you were returning raw results, then you might want to consider wrapping them in a search-results object to provide some meta-data.

Ah! So wait, what if instead of search results, you are indicating a collection of RESTful resources?

GET /items

In this case, I would still return a 200 with a body that says there are no items.

What if, you were trying to retrieve a particular resource?

GET /items/1234

In this case, yes, you want to imply that item 1234 does not exist, and you should return a 404.