amit kumar
amit kumar

Reputation: 21

How to run a new function in rest api codeigniter

I am creating a rest api in using codeigniter framework. I downloaded code from following link: https://github.com/halimus/codeigniter-rest-api

Now in postman, if I put following url with GET or POST method then api is running: "http://localhost/codeigniter-rest-api-master/api/users". But if I add a new function "testing" and hit following url then it's showing error "404 Page not found" "http://localhost/codeigniter-rest-api-master/api/testing"

Here is my code of "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);
        } 
    } 
}

Upvotes: 0

Views: 540

Answers (1)

Carl Ortiz
Carl Ortiz

Reputation: 465

You'll gonna need to rename your function to {resource}_{HTTP_verb}.

In your case testing_get.

Where testing is the resource and get is the HTTP verb.

When you access the API using the URI: http://localhost/codeigniter-rest-api-master/api/users/testing/ in GET method. testing_get will be called.

You can read it in detail here: https://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter--net-8814

Upvotes: 0

Related Questions