Yii 1.1: Simple Web APIs for your Yii App

9 followers

How it Works

Its very common now-a-days to have Mobile app for web apps. For Mobile apps we need web APIs to fetch data or even post/update on web. We found a very simple method to make such interface. Mobile App can call plain get or post request and receive data back in JSON format. JSON is relatively easy for mobile app to handle while plain standard GET/POST request for easy for Web server to handle. This mixed approach saves lot of time on server side. We not really need to handle actual REST requests and still be able to exchange data between web and mobiles or ajax java-scripts or even node.js.

How API url would look like

Web : http://example.com/post/index [ returns HTML Web page ] API : http://example.com/api/post/index [ returns JSON Array ] [ please notice the 'api' ]

Procedure:

  • Create a test project in yii framework.
  • Enable URL as path as per doc: http://www.yiiframework.com/doc/guide/1.1/en/topics.url
  • Create new module named 'api' using gii.
  • Copy existing controller into newly created module .
  • Create new function in controller.php named sendJSONResponse()
  • Replace render() calls with sendJSONResponse() and pass php array.

And you are almost done.

public function sendJSONResponse( $arr)
    {
        header('Content-type: application/json');
        echo json_encode($arr);
        Yii::app()->end();
    }

API Action Code

This is how you can modify you actual action code.It should not have render code. I have a array having few parameter like status, action, controller which i want to return back to mobile app. This is required if your APIs are called asynchronously. So response should have details on which action was called.

public function actionLogout()
    {
        $arr = array('controller'=>$this->id, 'action'=>$this->action->id,'status' =>'OK');
        Yii::app()->user->logout();
        $this->sendJSONResponse($arr);
    }

Example Code

http://iseetv.biz/api/ http://t1.toxsl.in/download.php?file=eWlpX2FwaXRlc3Quemlw [ Only for 30 days ]

Total 3 comments

#16804 report it
suhad at 2014/03/30 05:32am
Android

Good

#16235 report it
shiv at 2014/02/02 01:59am
Updated.

Oh i see 2 negative ratings already. I have been busy with work and could not update in time. Please check now. I would share sample working test code as well.

#16186 report it
trond at 2014/01/27 03:37am
Interesting concept

This article is currently very sketchy, but if you explain each step in detail, it could become interesting. Would love to see some code samples as well.

Leave a comment

Please to leave your comment.

Write new article
  • Written by: shiv
  • Updated by: CeBe
  • Category: How-tos
  • Yii Version: 1.1
  • Votes: +2 / -2
  • Viewed: 7,205 times
  • Created on: Jan 23, 2014
  • Last updated: Apr 14, 2014
  • Tags: API, JSON