For instance, a common pattern is http://
Anyway, in Yii it's really easy. There is a longer example here but I will just cover the outline:
- Download Yii as normal, you may or may not want to scaffold any database tables at this point (I just call into a separate database and didn't need to)
- Setup the rules in the url manager in your config so that they redirect the incoming /api/model/action into the relevant controller:
array('user/get', 'pattern'=>'api/user', 'verb'=>'GET,POST' ),
array('userdata/get', 'pattern'=>'api/userdata', 'verb'=>'GET,POST'),
- Remove any other default routes that you do not need from here (such as the post/posts routes)
- Note, I am not using the action in the url, it is implied because I have a very simple REST service that only "GET"s.
- The routes above will automatically redirect to UserController::getAction and UserDataController::getAction the bits in bold are added by the framework when resolving the request (btw this is standard Yii behaviour). Note you can also restrict which HTTP verbs are allowed. If you call the route with an incorrect verb you will get a "no route found" error. In my case I allow GET and POST but I will return a specific error if the user tries to use GET.
- Add a relevant method to your controller classes:
public function actionGet()
if ( Yii::app()->request->requestType != "POST")
$this->_sendResponse(400, CJSON::encode("Invalid verb. Method requires POST"));
- Since this is a REST API, it is almost certain that you will be returning JSON encoded data, including with the errors. Note the helper functions for these are defined in the longer tutorial linked above and are added to components\Controller.php (the base class for controllers)
- Remove any default functionality that you don't want/need like login pages and contact forms.
- Optionally redirect/customise standard errors and modify the url manager to not include index.php in the url if required.
- That's it!