使用CodeIgniter的RestApi发布请求 [英] RestApi Post request using CodeIgniter
问题描述
我正在实现自己的API。我正在关注此处的教程一个>。即使我遵循它,我也很难使我的API正常工作。
I am implementing my own API. I’m following the tutorial here. Even though I follow it I had a hard time to make my API working.
我没有得到与CodeIgniter REST Server和CodeIgniter REST Client的区别。如果有人向我解释这将是一个很大的帮助。
I didn’t get what is the difference with CodeIgniter REST Server and CodeIgniter REST Client. If someone explain it to me it would be a big help.
现在,我真正的问题是:我在下面有一个控制器,并且我扩展了编写的REST_Controller.php在教程中。
And now my real problem is: I have a controller below and I extends the REST_Controller.php which was written in the tutorial.
class Call extends REST_Controller
{
public function news()
{
// initialize you setting
$config = array(
'server' => 'localhost'
);
$this->rest->initialize($config);
// Set method of sending data
$method = 'post';
// create your param data
$param = array(
'id' => '1',
'name' => 'test'
);
// url where you want to send your param data.
$uri = 'http://192.90.123.908/api_v1/index.php';
// set format you sending data
$this->rest->format('application/json');
// send your param data to given url using this
$result = $this->rest->{$method}($uri, $params);
$data=array(
'id' => '1',
'name' => 'test'
);
print_r($data);
}
}
访问此URL时我期望的是 http://localhost/website/index.php/call/news
。我将得到一个JSON响应。但是我得到的是
{ status:false, error: Unknown method}
。我找不到问题所在。
What I expected is when I access this url http://localhost/website/index.php/call/news
. I will get a JSON response. But what I get is
{"status":false,"error":"Unknown method"}
. I can’t find what is wrong.
推荐答案
从此处下载或克隆分支> https://github.com/chriskacerguis/codeigniter-restserver
Download or clone the branch from here https://github.com/chriskacerguis/codeigniter-restserver
拖动并将application / libraries / Format.php和application / libraries / REST_Controller.php文件拖放到应用程序的目录中。要在控制器顶部使用require_once将其加载到范围中。此外,从应用程序/ config中的应用程序/ config中复制rest.php文件。
Drag and drop the application/libraries/Format.php and application/libraries/REST_Controller.php files into your application's directories. To use require_once it at the top of your controllers to load it into the scope. Additionally, copy the rest.php file from application/config in your application's configuration directory.
<?php
require APPPATH . '/libraries/REST_Controller.php';
class Call extends REST_Controller
{
public function news_get()
{
//Web service of type GET method
$this->response(["Hello World"], REST_Controller::HTTP_OK);
}
public function news_post()
{
//Web service of type POST method
$this->response(["Hello World"], REST_Controller::HTTP_OK);
}
public function news_put()
{
//Web service of type PUT method
$this->response(["Hello World"], REST_Controller::HTTP_OK);
}
public function news_delete()
{
//Web service of type DELETE method
$this->response(["Hello World"], REST_Controller::HTTP_OK);
}
}
使用用于调试API的邮递员开发环境工具
这篇关于使用CodeIgniter的RestApi发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!