Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should POST request return 404 if reference to other entity fails?

Tags:

rest

I'm building an API which operates on a noun Foo. When a caller creates an instance of Foo with a POST request, they are required to provide an ID to a second noun, Bar. If the ID they provided is of the right type but there is no Bar with that ID, is 404 the right response?

like image 603
ehdv Avatar asked Nov 27 '13 18:11

ehdv


3 Answers

I think it depends on whether the ID is in the URL or not. The URL is the address for a resource, if the ID is in the URL and no item with this ID exists, or you don't provide it at all, then the URL is invalid, so no resource could be found, so that's a 404.

However, if the ID is not in the URL but in the data from the POST request, and the URL is a valid address to a resource, then a 400 Bad Request should be returned.

like image 114
gitaarik Avatar answered Oct 24 '22 06:10

gitaarik


In short: No. Your API should be "user-friendly" meaning, if there is an error it should return it in a way that the user can figure out what the problem was. Returning 404 is like saying that the service was not found which is not true. The response should be 403 - cause it could be that the resource with the ID that the client tries to approach belong to a different client!

In addition, the response should contain an error message/code (in the body) which can be parsed and analyzed by the client.

like image 20
Nir Alfasi Avatar answered Oct 24 '22 08:10

Nir Alfasi


I would suggest using HTTP 400 (Bad Request).

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1. One could interpret 400 as a generic indication that the client did not form the request correctly.

One could also make a case for returning a 500 response. If the client believes that the Bar reference is valid, then the server's failure to process this request could be viewed as exceptional. This could happen for example if the reference is valid, but the a different client deletes it. In this scenario, the first client is not doing anything wrong.

like image 28
EJK Avatar answered Oct 24 '22 07:10

EJK