0

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?

Leon
  • 181
  • 1
  • 2
  • 11
  • 1
    us this https://httpstatuses.com/ so that if in the future you plane to make it as API and some one is using it as API, it will be clear and self explnatory – Jatin Mehrotra Oct 12 '20 at 05:57

1 Answers1

1

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 :

if (res.status == 200){
    // user found
} else if (res.status == 204) {
    // user not found
} else {
    alert('An error occured')
}
IQbrod
  • 1,590
  • 1
  • 2
  • 20
  • I see. So it seems that I still need to use the proper way in order to return the response. But on the client side, aren't all the other response code, other than `200`, will be handled under my `else` statement? What I mean is, as long as I have the `else` stated then it should be fine. So we will just assume that there is an error occurred on the server side. The error can by anything including not found, or already exist, or code error. After all, what we want to show the user is just `found` or `not found`. – Leon Oct 24 '20 at 04:49
  • Your back should return `200` with user for found and `204` for not found but accepted. Your front should handle `200` and `204` as accepted status and go in your `else` block otherwise – IQbrod Oct 24 '20 at 08:37