I've been working with REST API CodeIgniter for more than a year and usually when I want to return any response I will return 200
for all kind of request. I know that there are status code provided for all response but I am actually quite wondering, is it wrong if I use 200
for all response? And determine the data status with true
and false
.
Here is the sample code that I always use. Let's say to check whether the user is exist or not.
CodeIgniter REST API
$user = [ 'id' => 1, 'name' => 'John Doe' ];
$this->response([
'status' => !empty($user) ? true : false,
'user' => $user
], REST_Controller::HTTP_OK);
React Native
try {
const res = await axios.get('https://www.example.com/retrieve-user?user_id=3');
if (res.status == 200){
if(res.data.status == true){
// user found
} else {
// user not found
}
} else {
alert('Internal server error.')
}
} catch (err) {
console.error(err);
}
Based on the example, I am actually depending on the status code 200
to determine if there is an error in the server (code error, invalid request, etc).
So my question is, is it okay to stick with this method?
Given your API, yes handling code
200
seems enough as your API might not return any other HttpCode.Given a bigger API (even simple), no.
Your API might return a
204
/404
if no user if found with given id.Your API might return a
503
if your API is under deployment (and unavailable) or under maintenance, and you may retry 30 seconds later.Your API might reject request if a given header is missing (Content-Type ...) and return a
400
...EDIT 1 :