I was researching about best practices for standardised JSON response formats for APIs, according to various sources available online general consensus looks something like this:
//Successful request:
{
"success": true,
"data": {
/* requested data */
},
"message": null
}
//For failed request:
{
"success": false,
"data": {
/* error data */
}
"message": "Error: bad stuff"
}
My question is: what is the reasoning behind the "success" parameter inside the response body? Shouldn't the info about whether the request was successful or not be determined from HTTP status codes instead of additional parameters like "success"?
Also, many HTTP clients, like axios, will throw exceptions based on response status code, which can simplify the handling of requests. Example of using axios and status code exceptions instead of "success" parameter:
axios.get('/api/login')
.then((response) => {
// The request was successful do something
}).catch(function (error) {
if (error.response) {
// Request made and server responded with HTTP status code out of 2xx range
console.log(error.response.data);
// Handle error json data in body
console.log(error.response.status);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
I would appreciate it if someone could give me a few reasons why the standard with "success" param inside the json response is so common. There is probably something important I am missing related to motivation for such an approach.
A few potential reasons why you may wish to do this are:
the fact that some HTTP clients treat anything other than 2xx as an "exception" to be thrown, which can hide differences between transport errors (like no connection, invalid firewall, invalid endpoint/URL, etc.) and actual API errors (bad API key, request validation rules, etc.), which could both end up being thrown as errors, which leads to extra work in determining which it was and extracting the actual API error text
responses that aren't accurately / completely represented by normal status code, or even multi action requests, where you have >1 API action in a single HTTP request and each one may succeed or fail individually, in which case either a 2xx or 4xx would not be accurate
I personally prefer to inspect the JSON for errors instead of hoping that the language I'm using will easily differentiate between different kinds of errors. Java and C# for example would allow me to do multiple different catches of specific exceptions on a single try, but in JavaScript where anything can be an error and each try only allows a single catch, it's messier to separate transport errors from API errors
External links referenced by this document: