codedgift
codedgift

Reputation: 69

How can I define my function when using REST API in CodeIgniter?

I created a controller named Api.php then I extended the Rest_Controller. I noticed that I can only use index_get() when creating a function in this controller

<?php

class Api extends REST_Controller{

    public function __construct()
    {
        parent::__construct();

    }

    public function index_get(){
        $car_id = $this->get('car_id');
        if(!$car_id){

            $this->response("No Car ID specified", 400);

            exit;
        }

        $result = $this->model_getvalues->getCars( $car_id );

        if($result){

            $this->response($result, 200); 

            exit;
        } 
        else{

             $this->response("Invalid Car ID", 404);

            exit;
        }
    }

}

but when I try creating my desired function like getAllCars() instead of index_get() I get an error message telling me unknown function.

How can I define my own function instead of using index_get() when using rest api library in CodeIgniter?

Upvotes: 0

Views: 1530

Answers (3)

Ayush ASh
Ayush ASh

Reputation: 1

All you have to do is change function index_get() to getAllCars_get(),

`<?php

class Api extends REST_Controller{

public function __construct()
{
    parent::__construct();

}

public function getAllCars_get(){
    
   //your code
    
}

} ?> ` Like this

Upvotes: 0

codedgift
codedgift

Reputation: 69

Thanks i have been able to figure it out, i just found out that the name before the _get is what matters to the url i.e when one has a method like getCars_get, you will have to call it using just getCars without the _get attach to it, it work for me. it means that one can have more than _get method in the API controller.

Upvotes: 1

Ferry Sanjaya
Ferry Sanjaya

Reputation: 224

By default on https://github.com/chriskacerguis/codeigniter-restserver#handling-requests the method is index_get(),another way to use your own method is play with the HTTP GET parameter ex:

if($this->get('car_id') == 'all'){
  //your own function here
}

Or if you really want to create your own method you can refer on this http://programmerblog.net/create-restful-web-services-in-codeigniter/

Upvotes: 0

Related Questions