Thursday, August 7, 2014

How to implement REST using Yii

DONT YOU DARE LEAVE YII!

Don't jump in their wagon yet. Stay on the boat. Here is how to create REST API using Yii

I will be using yii version 1.15

its easy actually just paste these

       array('api/list', 'pattern'=>'api/<model:\w+>', 'verb'=>'GET'),
       array('api/view', 'pattern'=>'api/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
       array('api/update', 'pattern'=>'api/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
       array('api/delete', 'pattern'=>'api/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),

in your main.php

here is my complete configuration

'rules'=>array(
       array('api/list', 'pattern'=>'api/<model:\w+>', 'verb'=>'GET'),
       array('api/view', 'pattern'=>'api/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
       array('api/update', 'pattern'=>'api/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
       array('api/delete', 'pattern'=>'api/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),


Now that you pasted that code. Create a ApiController.php file on your controllers folder.

heres the complete code of that file

class ApiController extends Controller
{
    // Members
    /**
     * Key which has to be in HTTP USERNAME and PASSWORD headers 
     */
    Const APPLICATION_ID = 'ASCCPE';
 
    /**
     * Default response format
     * either 'json' or 'xml'
     */
    private $format = 'json';
    /**
     * @return array action filters
     */
    public function filters()
    {
            return array();
    }
 
    // Actions
    public function actionList()
    {
    }
    public function actionView()
    {
    }
    public function actionCreate()
    {
    }
    public function actionUpdate()
    {
    }
    public function actionDelete()
    {
    }
}

And you are DONE!..

here an example code from my ApiController

    public function actionView()
    {
        // header('Content-Type: application/json');
        /*retrieve json string with contact id */
        if (class_exists($_GET['model'])) {
            $foundContact = new $_GET['model'];
            $criteria = new CDbCriteria;
            $criteria->compare("rec_id",$_GET['id']);
            $foundContact = $foundContact::model()->find($criteria);
            echo CJSON::encode($foundContact);
        }else{
            throw new CHttpException(404,"Sorry we cant find that contact");
        }


        /*return the full data*/
    }


No comments:

Post a Comment