Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Creating RESTful API in cakephp

    • 0
    • 4
    • 4
    • 1
    • 0
    • 0
    • 0
    • 0
    • 6.49k
    Comment on it

    This tutorial will help you to learn how to create rest api in cakephp. For this we need to follow the following steps:


    Step1: Create a database and a table say "users"


    Step2: Now we will create the Users Model, Veiw and Controller.

        users model:
    
        class User extends AppModel {
    
    
        }
    

    Step3: Create a restful controller: RestUsersController.php

    <?php 
    
    class RestUsersController extends AppController {
    
        public $uses = array('User');
        public $helpers = array('Html', 'Form');
        public $components = array('RequestHandler');
        public function index() {
            $users = $this->User->find('all');
            $this->set(array(
                'users' => $users,
                '_serialize' => array('users')
            ));
        }
    
        public function add() {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                 $message = 'Created';
            } else {
                $message = 'Error';
            }
            $this->set(array(
                'message' => $message,
                '_serialize' => array('message')
            ));
        }
        public function view($id) {
            $phone = $this->User->findById($id);
            $this->set(array(
                'phone' => $phone,
                '_serialize' => array('phone')
            ));
        }
        public function edit($id) {
            $this->User->id = $id;
            if ($this->User->save($this->request->data)) {
                $message = 'Saved';
            } else {
                $message = 'Error';
            }
            $this->set(array(
                'message' => $message,
                '_serialize' => array('message')
            ));
        }
        public function delete($id) {
            if ($this->User->delete($id)) {
                $message = 'Deleted';
            } else {
                $message = 'Error';
            }
            $this->set(array(
                'message' => $message,
                '_serialize' => array('message')
            ));
        }
    }
    ?>
    

    step 4: Now we will step a test ClientController

    This controller uses CakePHPs HttpSocket class to make HTTP request to the REST service. This client can be run from a separate application on a different server to truly test communication between the client and the REST service.

    <?php
    
    App::uses('HttpSocket', 'Network/Http');
    class ClientController extends AppController {
        public $components = array('Security', 'RequestHandler');
    
        public function index(){
    
    
        }
    
        public function request_index(){
    
            // remotely post the information to the server
            $link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_users.json';
            $data = null;
            $httpSocket = new HttpSocket();
            $response = $httpSocket->get($link, $data );
            $this->set('response_code', $response->code);
            $variables = $this->set('response_body', $response->body);
    
            $this -> render('/Client/request_response');
        }
    
        public function request_view($id){
    
            $link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_users/'.$id.'.json';
            $data = null;
            $httpSocket = new HttpSocket();
            $response = $httpSocket->get($link, $data );
            $this->set('response_code', $response->code);
            $this->set('response_body', $response->body);
    
            $this -> render('/Client/request_response');
        }
    
        public function request_edit($id=1){
    
            // remotely post the information to the server
            $link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_users/'.$id.'.json';
            $data = null;
            $httpSocket = new HttpSocket();
            $data['Phone']['name'] = 'Updated Phone Name';
            $data['Phone']['manufacturer'] = 'Updated Phone  Manufacturer';
            $data['Phone']['name'] = 'Updated Phone  Description';
            $response = $httpSocket->put($link, $data );
            $this->set('response_code', $response->code);
            $this->set('response_body', $response->body);
    
            $this -> render('/Client/request_response');
        }
    
        public function request_add(){
    
            // remotely post the information to the server
            $link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_users.json';
            $data = null;
            $httpSocket = new HttpSocket();
            $data['Phone']['name'] = 'New Phone';
            $data['Phone']['manufacturer'] = 'New Phone Manufacturer';
            $data['Phone']['name'] = 'New Phone Description';
            $response = $httpSocket->post($link, $data );
            $this->set('response_code', $response->code);
            $this->set('response_body', $response->body);
    
            $this -> render('/Client/request_response');
        }
    
        public function request_delete($id=4){
    
            // remotely post the information to the server
            $link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_users/'.$id.'.json';
            $data = null;
            $httpSocket = new HttpSocket();
            $response = $httpSocket->delete($link, $data );
            $this->set('response_code', $response->code);
            $this->set('response_body', $response->body);
    
            $this -> render('/Client/request_response');
        }
    }
    
    ?>
    

    step 5: Now to check if we are the RestUsersController or not:

    We tell the security component to unlock the various REST actions for the HTTP requests, otherwise.Hence we change the AppController.php file:

    public function beforeFilter() {
    
        if(in_array($this->params['controller'],array('rest_users'))){
            // For RESTful web service requests, we check the name of our contoller
            $this->Auth->allow();
            // this line should always be there to ensure that all rest calls are secure
            //$this->Security->requireSecure();
            //$this->Security->unlockedActions = array('index','edit','delete','add','view');
    
        }else{
            // setup out Auth
            $this->Auth->allow();        
        }
    }
    

    step 6: For making our application "RESTful" we modify our routes.php as below.

    //In app/Config/routes.php...

    Router::mapResources('users');
        Router::parseExtensions()
    

    For more information see the link below:

    http://miftyisbored.com/complete-restful-service-client-cakephp-tutorial/

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: