Should HTTP Status be used in Restful Error Responses? - json

I'm writing a Restful API and I have to return error message but I'm not sure on which route to go.
Route 1 - HTTP Status
Use HTTP error status when the client sends bad data
Ex: 401 - Not authorized, 410 - Model does not exist, 412 - Model Validaiton Error, etc
Route 2 - JSON Success or Error Failure
The API returns json and I am considering returning everything with the http header 200, but then in my JSON handle errors and success
Ex:
{ "status" : "error", "message" : "Model validation error", "data" : ["user name required", "user email required"] }
Which route should I go and why? Advantages and disadvantages.

I'm writing a Restful API and I have to return error message but I'm
not sure on which route to go.
Route 1 - HTTP Status
Use HTTP error status when the client sends bad data
HTTP status codes should absolutely be used in any web service implementation claiming to be RESTful. The core principle of the specification is leveraging and extending the Web to fully support transfer of representational state. To allow for interoperation with existing Web infrastructure a REST implementation should indicate status of requests via appropriate HTTP status codes. For example:
200 - Ok
201 - Content Created
401 - Unauthorized
403 - Forbidden
500 - Server Error
501 - Not Implemented
When responding with many of these statuses, its also allowed by the HTTP specification to include an entity representation in the response body. In the case of 'normal', non-error responses, this representation will normally be of the entity that is being 'operated' on by the HTTP request. In the case of error responses the representation, if included, should provide more information on the error that occurred. This is where we segue to your option 2.
Route 2 - JSON Success or Error Failure
The API returns json and I am considering returning everything with
the http header 200, but then in my JSON handle errors and success
You should absolutely not return a 200 OK for all responses. Many well implemented HTTP clients depend on the status code in the response to determine wether it succeeded or not. Always responding with a 200 OK can cause third party client libraries to incorrectly process the incoming data, and also puts a requirement on your client to parse the response body in order to determine if an error actually happened or not.
Having said that, adding additional information about the error that occurred can be very helpful, so definitely do consider adding it to the response body. Your proposed format looks just fine, though to be honest the status element is redundant, assuming you use HTTP status codes appropriately. Something more like:
{
"message": "Model validation error",
"data": [
"user name required",
"user email required"
]
}

Related

Should REST API always return response with a message?

I'm not sure whether I should include success message in the response when I create an API server.
Like when you PUT something to the API server and the backend creates something successfully, you can get a response with 201 status code.
Does the API server should include a message like:
{
"message": "Successfully created."
}
as JSON in the response?
I agree with VoiceOfUnreason: it not is mandatory, but I usually return
{"status":"ok"}
If I need to return some content
{"status":"ok","result":{.....}}
And, in case an error occurs, I still prefer to return a 200 handling the error at the application level
{"status":"ko","errorMessage":"Something went wrong!"}
Fabio
Should REST API always return response with a message?
It's not required - we have 204 (No Content) and 205 (Reset Content) in the standard because there are cases where a response without a body makes sense.
But in common cases where we are sending a 200/201, I would expect to see a response body describing the status of the action
The 201 response content typically describes and links to the resource(s) created.
No for example, for 204 responses we must not include message body. {success: true} is redundant.
In practice (or should I say in later version of jquery), empty response for application/json content type raises error. I kind of understand the argument that because it's application/json it must have a valid json body. So, empty response for application/json content type would be 'null' or '{}' which are valid json.
There's another way which should work for jquery, that is not returning application/json for empty responses. Just use text/plain or something and make sure client can handle that type.

How to distinguish a deliberate, controller-generated 404 from an actual error in a REST API?

In a JSON-REST service architecture (following these patterns for methods and response codes) we often need to generate a deliberate 404 response - for example, if GET /users/123 is routed to a controller, which is then unable to find a User entity with ID 123, we return a 404 response, which in many cases will include a JSON payload with an error message/code/etc.
Now, when we provide a client for a specific API, we want the client to behave differently under different conditions. For example, if we point the client to the wrong host, we might get a 404 not found from that host - as opposed to the 404 we might get for an invalid User ID if we do reach the service.
In this case, a "404 User ID not found" is not an error, as far as the client is concerned - as opposed to any other "404 Not Found", which should cause the client to throw an exception.
My question is, how do you distinguish between these 404 errors?
Solely based on the response?
By adding a header to indicate a valid response?
Or some other way?
It is OK to return 404 in both cases. As 4xx codes are client relevant codes, it is also OK to return content even if there was an error.
Now, deciding what kind of 404 it was can be decided based on the body of the response. Remember, that the response should carry a mime-type that is compatible with the Accept header the client supplied. So if the client "knows" your specific error-describing format, your server can answer with a more detailed description.
This way both the server can decide whether the client would understand a detailed response with the 404, and the client also understands when it just got a regular 404, or one with a message it can process.
This would be both semantically correct, and compatible with HTTP.

Http response exceptions format

Does anyone know what is the best format to return an HTTP response error to the client when facing an exception? A format to handle the error in a dynamic way and the easiest way to catch the exception between server and client
i suggested the following, but i need to get the best format for the error response:
{
"FLAG": "ERROR",
"TEXTEN": "SERVER ERROR – BAD REQUEST"
}
One good solution would be to send back the error code in the answer's headers, using the standardized HTTP codes from the HTTP protocol.
You can also add you own error code and a corresponding human readable message in the JSON body to provide more informations on the encountered error.
For example, for a Bad Request error, the corresponding HTTP code is 400. So you should send back the HTTP code 400 in the response header and the corresponding HTTP message (Bad Request). But some programming languages does not offer out of the box features to read the message. To be sure that the user can read it properly, you can also put it in the JSON body if you want.

Suggested JSON structure for Exceptions?

Out of curiosity, are there any popular standards for returning server side exceptions (and corresponding details) in an API that returns JSON? The exceptions could be anything from uncaught exceptions in the code or thrown exceptions put in place by the developer.
Currently I'm setting the HTTP Status Code according to their Wiki definitions'
My JSON response would look something like this:
HTTP Code: 401
{'error': 'Authentication required.', 'message': 'You must be authenticated to perform that action.'}
You can take a look at JSON-RPC (http://en.wikipedia.org/wiki/JSON-RPC).
In case of success, the response is like this:
{
"result": ...(returned data)...
...
}
and in case of error, the response is like that:
{
"error": ...(error details)...
...
}
When the error occured, "error" property must be present and "result" property must not be returned. In case there was no error, "error" property must not be set. This way you can distinguish errors from successful responses based solely on the content of the response, without the need to check the headers (like response codes).
The standard structure of native ECMAScript error objects is:
{
name: ...,
message: ...
}
where "name" is the type of the error (the name of the corresponding constructor, like "Error", "SyntaxError", etc.). In your example, you could use the name "AuthentificationError", for instance.
Yes you can do the same.
As we know that Web servers allow us to create custom error pages for HTTP errors, in those custom error pages you have to serve the JSON reply
Example:
Add the following to your WEB-INF/web.xml:
<error-page>
<error-code>401</error-code>
<location>/autherror.jsp</location>
</error-page>
In the autherror.jsp file code the required logic to accomplish your needed JSON reply.
Try being a bit more verbose regarding the error you are sending. This structure has been suggested in some places to give sufficient information both for users and developer using your API
"error":{
"code":"410",
"long":"410001",
"message":"cannot connect to DB",
"developer":"Connection to the DB was unsuccessful due to ...",
"documentation": "mysite.com/help/errors/..."
}
Return the correct HTTP code for error. It is bad practice to return code 200 with error.
Extend the code with your own error IDs
Provide short message that roughly outlines the cause of the error. Consider adding more detailed message for the developers. Have in mind that API error messages are 99.9% of the time read by developers so make them happy by providing technical details (within reason) so that they can resolve ASAP.
In case you keep public documentation about your api and error codes, simply add the url.

Why should JSON have a status property

I stumbled over a practice that I found to be quite widespread. I even found a web page that gave this a name, but I forgot the name and am not able to find that page on google anymore.
The practice is that every JSON response from a REST service should have the following structure:
{
"status": "ok",
"data": { ... }
}
or in an error case:
{
"status": "error",
"message": "Something went wrong"
}
My question: What is the point why such a "status" property should be required in the JSON? In my opinion that is what HTTP status codes were made for.
REST uses the HTTP means of communication between client and server, for example the "DELETE" verb should be used for deleting. In the same way, 404 should be used if a resource is not found, etc. So inline with that thinking, any error cases should be encoded properly in the HTTP status.
Are there specific reasons to return a HTTP 200 status code in an error case and have the error in the JSON instead? It just seems to make the javascript conditional branches more complex when processing the response.
I found some cases where status could be "redirect" to tell the application to redirect to a certain URL. But if the proper HTTP status code was used, the browser would perform the redirection "for free", maintaining the browsing history properly.
I picture mainly two possible answers from you:
Either there are two quarreling communities with their favorite approach each (use HTTP status always vs. use HTTP status never)
or I am missing an important point and you'll tell me that although the HTTP status should be used for some cases, there are specific cases where a HTTP status does not fit and the "status" JSON property comes into play.
You are right. I think what you are seeing is a side-effect of people not doing REST correctly. Or just not doing REST at all. Using REST is not a pre-requisite for a well-designed application; there is no rule that webapps have to be REST-ful.
On the other hand, for the error condition, sometimes apps want to return a 200 code but an error to represent a business logic failure. The HTTP error codes don't always match the semantics of application business errors.
You are mixing two different Layers here:
HTTP is for establishing (high-level) connections and transferring data. The HTTP status codes thus informs you if and how the connection was established or why it was not. On a successful connection the body of the HTTP request could then contain anything (e.g. XML, JSON, etc.), thus these status code have to define a general meaning. It does not inform you about the correctness or type (e.g. error message or data) of the response.
When using JSON for interchanging data you could certainly omit the status property, however it is easier for you to parse the JSON, if you know if it includes the object you were requesting or an error message by just reading one property.
So, yes, it is perfectly normal to return a 200 status code and have a "status": "error" property in your JSON.
HTTP status codes can be caused by a lot of things, including load balancers, proxies, caches, firewalls, etc. None of these are going to modify your JSON output, unless they completely break it, which can also be treated as an error.
Bottom line: it's more reliable to do it via JSON.