Home

A very simple JSON API

Published on 12/17/2010


See also “How to output related values in JSON”

Let’s assume you have a database table like this:

CREATE TABLE IF NOT EXISTS `tbl_cars` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dealer_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

And you create a standard controller and model using Gii.

To make a very simple JSON web service API, add this to the controller (don’t forget to change the access rules!):

public function actionGetCar($id)
{
  header('Content-type: application/json');

  $car = Cars::model()->findByPK((int)$id);

  echo CJSON::encode($car);

  Yii::app()->end();
}

And when you make a request like this /index.php/cars/getcar?id=3 (or like /getcar/id/3), you will get back a JSON formatted response, like this:

{"id":"3","dealer_id":"6","name":"honda"}

And now you have a real simple JSON API

... views