Friday, December 17, 2010

A very simple JSON API

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

10 comments:

  1. Hi Neil,

    The problem is that it always returns a error on header('Content-type: application/json');

    Cannot modify header information - headers already sent by.

    What I'm a doing wrong?

    ReplyDelete
    Replies
    1. I had the same problem and the issue was that one of my class had a space just after definition of <?php make sure no space.

      Delete
  2. you should avoid sending content back. this could also be from an invisible character in your source code getting sent back. are you developing on windows and running the server on linux?

    ReplyDelete
  3. What about the other way around? When you want to "POST" JSON data and map into to Yii objects?

    ReplyDelete
  4. I'm waiting for the same.., the problem is the entry point information have to be sent to the controller using the _form.php file the Gii produces... so, how can we post information, run the validation and also customize the error handling to return a message in JSON format ???

    ReplyDelete
  5. change access rules to what Sir??

    ReplyDelete
  6. You super, this worked like a charm for me.....thnx a million

    ReplyDelete
  7. awesome ... i am looking for this ...very helpful

    ReplyDelete
  8. worked like charm...yeah in opposite way, how get it on the form...

    ReplyDelete