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"
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.