Simple Web APIs for your Yii App

  1. How it Works
  2. How API url would look like
  3. Procedure:
  4. API Action Code
  5. Example Code

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 ]

1 2
10 followers
Viewed: 32 437 times
Version: 1.1
Category: How-tos
Tags: API, JSON
Written by: shiv
Last updated by: CeBe
Created on: Jan 23, 2014
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles