使用rest api返回http状态代码

Gil*_*erg 4 php api rest http-response-codes http-headers

我在php中构建自己的rest api进行练习.我可以评估发送到我的api的http代码(post,put,delete,get).但是当我发出我的回复时,我真的只是打印出一个json.例如,我在我的api中建立了一个响应

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

无论如何我都没有操纵标题.从阅读stackoverflow,我知道我应该返回http响应代码以匹配我的api结果.如何构建我的api并返回响应代码.我只是不明白我是怎么做到的,因为现在我只是打印出一个json.

我不是要问哪些代码要返回.我只是想知道如何返回代码.

Edd*_* C. 13

你可以用这种方式重新思考你的代码

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,在流输出(JSON数据)之前,您可以按http_response_code($code)功能设置HTTP状态代码.

关于您在评论中的其他问题,是的,打印JSON数据是正确的方法.