返回的HTTP状态codeS用REST API [英] Returning http status codes with a rest api
问题描述
我建立我自己的REST API在PHP实践。我可以评估发送到我的API(POST,PUT,DELETE,得到)的HTTP code。但是,当我发出我的回答我真的我只是打印出一个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);
}
我无论如何也不能操纵头。从阅读计算器,我知道我应该返回的HTTP响应codeS符合我的API的结果。我怎样才能建立在我的API和返回响应codeS。我只是不明白我怎么能做到这一点,因为现在我只是打印出一个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.
我不要求其codeS返回。我只是想知道如何在一般的C $ CS返回$。
I am not asking which codes to return. I just want to know how to return codes in general.
推荐答案
您可以重新考虑你的code这样
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)
功能。
和有关意见的另一个问题,是的,打印的JSON数据是正确的方式。
And about your additional question in comment, yes, printing the JSON data is the correct way.
这篇关于返回的HTTP状态codeS用REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!