【问题标题】:How to run a new function in rest api codeigniter如何在rest api codeigniter中运行新功能
【发布时间】:2018-12-01 05:03:09
【问题描述】:

我正在使用 codeigniter 框架创建一个 rest api。我从以下链接下载了代码: https://github.com/halimus/codeigniter-rest-api

现在在邮递员中,如果我使用 GET 或 POST 方法输入以下网址,则 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);
        } 
    } 
}

【问题讨论】:

    标签: php rest codeigniter


    【解决方案1】:

    您需要将函数重命名为 {resource}_{HTTP_verb}。

    在您的情况下 testing_get。

    其中 testing 是资源,get 是 HTTP 动词。

    当您使用 GET 方法中的 URI:http://localhost/codeigniter-rest-api-master/api/users/testing/ 访问 API 时。 testing_get 将被调用。

    您可以在此处详细阅读: https://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter--net-8814

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 2019-01-25
      • 1970-01-01
      • 2021-06-26
      • 2014-05-28
      • 2023-02-15
      相关资源
      最近更新 更多