RestApi Post request using CodeIgniter

谁都会走 提交于 2019-12-11 16:48:45

问题


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.

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.

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

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.


回答1:


Download or clone the branch from here https://github.com/chriskacerguis/codeigniter-restserver

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

Use Postman Development Environment tool for debugging the API



来源:https://stackoverflow.com/questions/45566545/restapi-post-request-using-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!