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
Hi Neil,
ReplyDeleteThe 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?
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.
Deleteyou 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?
ReplyDeleteWhat about the other way around? When you want to "POST" JSON data and map into to Yii objects?
ReplyDeleteI'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 ???
ReplyDeletechange access rules to what Sir??
ReplyDeleteYou super, this worked like a charm for me.....thnx a million
ReplyDeleteawesome ... i am looking for this ...very helpful
ReplyDeletenice Post ...
ReplyDeleteworked like charm...yeah in opposite way, how get it on the form...
ReplyDelete