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.