我正在使用codeigniter框架创建一个rest api。我从以下链接下载了代码:https://github.com/halimus/codeigniter-rest-api
现在在poster中,如果我使用GET或POST方法放置以下url,那么api正在运行:"http://localhost/codeigniter-rest-api-master/api/users"。但如果我添加了一个新功能"测试"并点击以下网址,那么它显示错误"404找不到页面"http://localhost/codeigniter-rest-api-master/api/testing">
这是我的"Application/controller/api/users.php"代码:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH.'/libraries/REST_Controller.php';
class Users extends REST_Controller {
function __construct() {
parent::__construct();
$this->load->helper('api');
}
public function testing()
{
echo "hello world";
}
public function users_get(){
$this->load->model('Model_users');
$user_id = $this->get('id');
if($user_id === NULL){
$users = $this->Model_users->get_many_by(array('status' => array('active', 'inactive')));
if($users!=""){
// Set the response and exit
$this->response($users, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else{
// Set the response and exit
$this->response(array('status'=> false, 'message'=> 'The Specified user could not be found'), REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
}
}
// Find and return a single record for a particular user.
$user_id = (int) $user_id;
if ($user_id <= 0){
// Invalid id, set the response and exit.
$this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
$user = $this->Model_users->get_by(array('user_id' => $user_id, 'status' => array('active', 'inactive')));
if(isset($user['user_id'])){
$this->response(array('status'=> 'success', 'message'=> $user));
}
else{
$this->response(array('status'=> 'failure', 'message'=> 'The Specified user could not be found'), REST_Controller::HTTP_NOT_FOUND);
}
}
}
您需要将函数重命名为{resource}_{HTTP_verb}。
在您的情况下,testing_get。
其中 testing是资源,而get则是HTTP谓词。
当您使用URI访问API时:http://localhost/codeigniter-rest-api-master/api/users/testing/在GET方法中。将调用testing_get。
您可以在此处详细阅读:https://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter--net-8814