tags:

views:

163

answers:

8

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?

+13  A: 

Return 404 status code.

Byron Whitlock
+1  A: 

A GET should only retrieve something that exists.

So I would return a 404.

DJ
+1  A: 

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

Nathan
+4  A: 

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

Jim Ferrans
+5  A: 

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

stinkymatt
+1 That's not a bad idea.
Byron Whitlock
Decide on either 401 or 404 and stick with it for all IDs, whether they exist or not. You don't want a hacker finding out which IDs are worth something by analysing which ones returned which error code.
Christian Hayter
+3  A: 

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

eglasius
+2  A: 

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

MatthewMartin
A: 

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.

Jon Moore