2017-08-08 102 views
0

我正在實現我自己的API。我正在關注the tutorial here。即使我遵循它,我仍然很難讓API工作。使用CodeIgniter的RestApi Post請求

我沒有得到與CodeIgniter REST服務器和CodeIgniter REST客戶端有什麼不同。如果有人向我解釋這將是一個很大的幫助。

現在我真正的問題是:我在下面有一個控制器,並且擴展了本教程中編寫的REST_Controller.php。

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"}。我找不到有什麼問題。

+0

您正在使用教程7歲。 – Tpojka

+0

我認爲你必須實現你自己的REST類,而不是像現在這樣使用REST_Controller。它取決於請求類型。但是我們可能只發送POST請求。 – kishor10d

回答

0

下載或從這裏https://github.com/chriskacerguis/codeigniter-restserver

將克隆的分支,刪除應用程序/庫/ Format.php和應用程序/庫/ REST_Controller.php文件到您的應用程序的目錄。要在您的控制器的頂部使用require_once將其加載到作用域中。另外,從應用程序配置目錄中的application/config複製rest.php文件。

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

使用Postman Development Environment工具,調試API

+0

如果我的所有請求都是POST,那該怎麼辦?我應該爲每個請求創建單獨的控制器嗎?或用_post()創建方法? – kishor10d

+0

不,你可以使用相同的控制器只是創建方法和追加_post你的方法名稱 –