我有一个代码点火器rest api,使用这个库创建:https://github.com/chriskacerguis/codeigniter-restserver
对于我的POST方法,一旦成功创建了资源,我希望包含一个位置标头,其中包含一个获取新创建/更新的资源的URI。我不清楚该怎么做。有人尝试过类似的东西吗?
到目前为止,我只是将创建内容的细节添加到响应体中。。。但我最终想添加GET url作为位置头。
到目前为止,我的逻辑是这样的:
public function widget_post()
{
$new_widget_data = array(
'location' =>$this->post('location'),
'name' => $this->post('name'),
'cost' => $this->post('cost')
);
// validate post data
if (!$this->isvalidpost($new_widget_data)) {
$this->response("Invalid data",400);
}
// add to database
$res = $this->widget_model->notify_servers($new_widget_data);
$new_widget_data['results']=$res;
if ($res) {
//append GET url to return value
$new_widget_data['GET']=base_url()."/index.php/widgets/widget/".$new_widget_data['name'];
$this->response($new_widget_data,201); //HTTP Created 201
} else {
$this->response("Unable to process request",500); //HTTP Internal server error
}
如有任何建议,我们将不胜感激。谢谢
我不认为当前版本的库提供了实现这一点的方法。
您可以选择将php-header()函数与REST_Controller类提供的response()函数结合使用。
header("Location:Location/to/new/resources");
然后调用响应函数,确保设置了201代码。$this->响应($new_widget_data,201);
通常情况下,Location标头将默认触发重定向,因此请确保始终设置201代码。
http://php.net/manual/en/function.header.php
您是否尝试过重定向('widgets?widget='.$new_widget_data['name']);还是我没有抓住要点?