REST standard for GET on a resource that doesn'

2020-06-16 02:19发布

问题:

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?

回答1:

It depends on your security concerns a little bit. I would either send a 404 if it is OK that the guesser finds out if that user id does not exist, or send 401 for all attempts on unauthenticated accesses to any resource under /user



回答2:

Return 404 status code.



回答3:

404

That said, this assumes you first checked authorization to that operation -> /user/[id] and if the user wasn't allow to access Other users accounts you would return 401.

Never rely on the user not knowing user ids ...



回答4:

@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.



回答5:

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



回答6:

A GET should only retrieve something that exists.

So I would return a 404.



回答7:

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



回答8:

From your original question, with no authorization, this is clearly a 404. If you were to add authorization, then it would actually be acceptable to return a 404 for all unauthorized requests; this prevents random ID guessing by distinguishing 401 or 403 (exists, but unauthorized) from 404s (nonexistent) as some of the other answers suggest. Per the RFC:

10.4.5 404 Not Found ... This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.



回答9:

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.



标签: rest