Thursday, 11 April 2013

Creating a REST web service using Yii and PHP

This is the flavour of the month for budding web developers! Developing REST is pretty easy actually for two reasons. Firstly, a REST web service is actually only a web application since web applications already support most of what you want to call your web service with. The only things that might help are an MVC framework which allow you to abstract between the url that is called from the outside and the controller that handles the action. Secondly, REST uses standard HTTP syntax which is as old and well supported as the hills!

For instance, a common pattern is http:///api/model/action (although the action is sometimes inferred from the HTTP verb (like GET, POST, DELETE etc.). This might mean you have something like /api/user/put, /api/user/delete, /api/user/get which in traditional web development would point to three different directories/files but which you probably want to point to the same controller, say a UserController!

Anyway, in Yii it's really easy. There is a longer example here but I will just cover the outline:

  1. 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)
  2. Setup the rules in the url manager in your config so that they redirect the incoming /api/model/action into the relevant controller:
    'urlManager'=>array(
                'urlFormat'=>'path',
                'rules'=>array(
                                array('user/get', 'pattern'=>'api/user', 'verb'=>'GET,POST'   ),
                                array('userdata/get', 'pattern'=>'api/userdata', 'verb'=>'GET,POST'),
                       ),
            ),
  3. Remove any other default routes that you do not need from here (such as the post/posts routes)
  4. 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.
  5. 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.
  6. 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"));
                Yii::app()->end();
            }
    // etc....
  7. 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)
  8. Remove any default functionality that you don't want/need like login pages and contact forms.
  9. Optionally redirect/customise standard errors and modify the url manager to not include index.php in the url if required.
  10. That's it!


Post a Comment