7

I am building my own rest api in php for practice. I can evaluate the http code sent to my api (post,put,delete,get). But when I send out my response I really am just printing out a json. For example, I build a response in my api like this

    public function actionTest()
    {
        $rtn=array("id":"3","name":"John");
        print json_encode($rtn);
    }

I am not manipulating the headers in anyway. From reading stackoverflow, I understand that I should be returning http response codes to match my api results. How can I build on my api and return the response codes. I just don't understand how I can do it because right now I am just printing out a json.

I am not asking which codes to return. I just want to know how to return codes in general.

1
  • Would this be the way to go http_response_code(); Also, is printing the json the accepted way to send the response? Commented Jan 18, 2014 at 16:53

1 Answer 1

23

You could re-think your code this way

public function actionTest()
{
    try {
        // Here: everything went ok. So before returning JSON, you can setup HTTP status code too
        $rtn = array("id", "3", "name", "John");
        http_response_code(200);
        print json_encode($rtn);
    }
    catch (SomeException $ex) {
        $rtn = array("id", "3", "error", "something wrong happened");
        http_response_code(500);
        print json_encode($rtn);
    }
}

Basically, before stream the output (the JSON data), you can set the HTTP status code by http_response_code($code) function.

And about your additional question in comment, yes, printing the JSON data is the correct way.

Sign up to request clarification or add additional context in comments.

2 Comments

I used as you mention "http_response_code(500);" but still am not able to show status in header I user postman desktop application to call rest api
Hi @SachinSarola, please check that you don't send any output before calling $result = http_response_code(500). Also, please check the actual value returned in the $result variable to ensure that the operation completed succesfully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.