rjurado01
rjurado01

Reputation: 5535

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?

Upvotes: 12

Views: 9852

Answers (3)

Leonel Galán
Leonel Galán

Reputation: 7167

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

Upvotes: 12

Bojidar Stanchev
Bojidar Stanchev

Reputation: 555

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

Upvotes: 3

Richard Brown
Richard Brown

Reputation: 11436

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous XML instructions.

(found here)

Since this isn't the case I'd go for 404. The query was valid but no object found.

Upvotes: 0

Related Questions