I'm building an application with a REST-based API and have come to the point where i'm specifying status codes for each requests.
What status code should i send for requests failing validation or where a request is trying to add a duplicate in my database?
I've looked through http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html but none of them seems right.
Is there a common practice when sending status codes?
200
Ugh... (309, 400, 403, 409, 415, 422)... a lot of answers trying to guess, argue and standardize what is the best return code for a successful HTTP request but a failed REST call.
It is wrong to mix HTTP status codes and REST status codes.
However, I saw many implementations mixing them, and many developers may not agree with me.
HTTP return codes are related to the
HTTP Request
itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:
"403 Forbidden/Access Denied" may mean:
And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...
From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.
If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the HTTP server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as HTTP result, right?
Instead of this you may return 200 HTTP code with some options:
Also, some internet providers may intercept your requests and return you a 404 HTTP code. This does not means that your data are not found, but it's something wrong at transport level.
From Wiki:
Why not simply answer with something like this?
Google always returns 200 as status code in their Geocoding API, even if the request logically fails: https://developers.google.com/maps/documentation/geocoding/intro#StatusCodes
Facebook always return 200 for successful HTTP requests, even if REST request fails: https://developers.facebook.com/docs/graph-api/using-graph-api/error-handling
It's simple, HTTP status codes are for HTTP requests. REST API is Your, define Your status codes.
I recommend status code 422, "Unprocessable Entity".