问题
I'm building a REST interface for a database and I've run into a question.
Imagine I have the 'Item' table which has two columns 'id' and 'user_id' which is a foreign key to the 'User' table.
When doing a PUT request (to change an Item), the update will fail if the 'user_id' doesn't exist in the 'User' table.
My question is, should this response be a 400 or a 404? Part of me thinks 400, as it's bad data supplied by the requester. But technically a 404 because the user resource can't be found.
Can anyone shed some light on this?
Thanks in advance!! :)
回答1:
TLDR
I'm leaning towards a 400
because - depending on the information you're trying to provide/change, you don't necessarily want the client to know that the resource doesn't exist, it's just giving the client a bit too much information. 404
implies that you don't have that resource and if they try a few more times, they might find a resource that does exist.
400
I think this is a nice little article about REST states, it says (about 400
s):
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
404
Wikipedia(Not that i'm using is a definitive source, but just sayin') says:
The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible.
My 2 cents*
I guess 404
makes a bit more sense in the conventional sense, because it is not found
, however, sometimes you don't want to the client to know that your resource doesn't exist, so you try not to give it too much information, If I'm trying to get a resource and I get a 404
It tells me that If I keep trying I'll get a resource that does exist, but this one doesn't.
For most data you can safely use a 404
, but if you find yourself in a place where you're trying to be more conservative about your data, then maybe a 400
will do
PUT
Usually with PUT
requests you're looking to mutate the resource, the main errors that might occur are 'unauthorised change', 'resource not found' or 'invalid value'. Obviously there might be others, but let's assume that this is the case for now.
If you're trying to retrieve an attribute it's 'not found', but if you're trying to change something that doesn't exists I think a 'bad request' or a 400
would make more sense.
*: with RESTful APIs everyone has his own interpretation, I gave you mine :)
Good luck ;)
来源:https://stackoverflow.com/questions/31773088/rfc-404-or-400-for-relation-of-entity-not-found-in-put-request