REST standard for GET on a resource that doesn'

2020-06-16 02:03发布

The resource /user/12345 doesn't exist. Lets say the consumer is trying different ids randomly. There is no authorization. Any user can view any user. In a broader sense, my question is "What should you return if you do a GET on a resource that doesn't exist?"

Should I return an empty user for an id that doesn't exist or should I return an error message with proper status code?

What is the typical/usual/recommended practice?

标签: rest
9条回答
贪生不怕死
2楼-- · 2020-06-16 02:35

@Byron is right, return HTTP 404. You want to leverage all of the capabilities of HTTP, and these include response status codes. So if there is a client error, return a 4xx error code, and if your server code has an internal problem, return a 5xx error code, etc.

Richardson and Ruby's RESTful Web Services (O'Reilly) has a good discussion of this, and an appendix with all the most important HTTP error codes and when to use them.

查看更多
放我归山
3楼-- · 2020-06-16 02:35

A GET should only retrieve something that exists.

So I would return a 404.

查看更多
乱世女痞
4楼-- · 2020-06-16 02:36

My opinion: Return an empty 200.

Quite frankly, if a REST resource doesn't exist, it doesn't exist. That means return 404. In your case, however, 12345 is a parameter you are using to identify/lookup a return entity. Resource /user/{userId} does actually exist, so technically I don't believe it is proper to return a 404, although it's clear to see the argument for either side.

If you feel like returning two status codes exposes your system in some way, however, I'd say stick with an empty 200 OK.

查看更多
狗以群分
5楼-- · 2020-06-16 02:38

That looks like a 404 error to me - resource not found.

查看更多
相关推荐>>
6楼-- · 2020-06-16 02:47

If the user is authenticated and authorized, return 404. If the user is unauthenticated and unauthorized, send them to a page to get authorized.

查看更多
再贱就再见
7楼-- · 2020-06-16 02:52

Return 404 status code.

查看更多
登录 后发表回答