使用rest api返回http状态代码 [英] Returning http status codes with a rest api

查看:62
本文介绍了使用rest api返回http状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
    }

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

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.

推荐答案

你可以这样重新思考你的代码

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);
    }
}

基本上,在流式传输输出(JSON 数据)之前,您可以通过 http_response_code($code) 函数设置 HTTP 状态代码.

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

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

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

这篇关于使用rest api返回http状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆