How to use codeigniter rest api from Phil and Backbone.js to GET, POST , PUT, DELETE data?

621 views Asked by At

I'm working with Phil rest library for codeigniter. According to his documentation a rest api can have as many parameters as we want so, the url is structured as follows:

/method/{resource/value}

which translates into this

/users/id/1

and we can append more attributes, for example /users/id/1/order/desc

but, by default, backbone send requests as follows:

 /users/1 

THE HTTP VERB USED defines which action we are performing

So, this question is a 2 in 1. QUESTION 1 How can i define, from the client side backbone model perspective, a new url structure that matchs the Codeigniter interface from phil? QUESTION 2 Second, i would like to know if it possible to make Codeigniter library from Phil respond to more simple urls, just like those from backbone which hide the id and just passes the value

 instead of this -> /users/id/1  use this -> /users/1

EDIT

For question 2 i found that is possible to use URI segments from Codeigniter. But is there a better way to do this?

<?php defined('BASEPATH') OR exit('No direct script access allowed');

    /**
     * Example
     *
     * This is an example of a few basic user interaction methods you could use
     * all done with a hardcoded array.
     *
     * @package CodeIgniter
     * @subpackage  Rest Server
     * @category    Controller
     * @author      Phil Sturgeon
     * @link    http://philsturgeon.co.uk/code/
    */

    // This can be removed if you use __autoload() in config.php OR use Modular Extensions
    require APPPATH.'/libraries/REST_Controller.php';

    class Resource extends REST_Controller
    {
        function action_get(){
               $data = array('method'=>'PUT','id'=>$this->uri->segment(3));
               $this->response($data, 200); // 200 being the HTTP response code          
        } 
        function action_post(){
               $data = array('method'=>'POST','id'=>$this->uri->segment(3));
               $this->response($data, 200); // 200 being the HTTP response code          
        }     
        function action_delete(){
               $data = array('method'=>'DELETE','id'=>$this->uri->segment(3));
               $this->response($data, 200); // 200 being the HTTP response code          
        }    
        function action_put(){
           $data = array('method'=>'DELETE','id'=>$this->uri->segment(3));
           $this->response($data, 200); // 200 being the HTTP response code          
        }
}

To request information i just need to do /Resource/method/{id} Where the id is the value that we want to pass to our controller The HTTP Verb does the rest

Thank you very much.

0

There are 0 answers