Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which http status code returns, 404 or 422?

I have a Rails API application with the next resource: /images. All images have one owner.

To create a new image, I do next request to /images:

image_info = { owner_id: '1234', name: 'img1' }

post :create, :format => "json", :image => @image_info

In controller of images I do:

owner = User.find( params[:owner_id] )

If owner_id don't exists or is invalid, what error code should the backend return, 404 or 422 with owner_id: invalid?

like image 849
drinor Avatar asked Mar 13 '13 21:03

drinor


2 Answers

I'll change my answer to 422 because you couldn't finish processing the request. Unprocessable entity its a better match, you didn't request an object so "not found" doesn't make a lot of sense. At the end is your choice, just choose whatever feels better to you.

422 Unprocessable Entity (WebDAV; RFC 4918) The request was well-formed but was unable to be followed due to semantic errors

Source: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error

like image 183
Leonel Galán Avatar answered Oct 12 '22 18:10

Leonel Galán


First of all, I believe this question should not be specific to Ruby because it applies to most web applications.

According to mozilla's dev guide https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 :

The HyperText Transfer Protocol (HTTP) 422 Unprocessable Entity response status code indicates that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions.

I'd say go with code 422 because the request path was correct, so was the provided data, but there was no such entity. Also, it says in the description - the request should not be repeated without modification - this applies in the case. I'd say 404 is most appropriate when the request path is wrong. Using it for anything else is confusing for the one sending the request because it does not provide enough information. If you returned 404 in your case I would be confused and think I sent the request to the wrong uri. Hope that helps

like image 41
Bojidar Stanchev Avatar answered Oct 12 '22 18:10

Bojidar Stanchev