The quickest way to add RestAPI to your Yii 2 app. Part 2
As explained in the previous article, the example given in Yii 2 Guide about turning regular MVC apps into RESTful one is of a low quality, as it mixes certain things (refer to the previous article for details).
This article deals with this problem and show how to enable REST in Yii 2 Advanced Project Template by adding REST UserController directly to frontend application in that template and thus allowing to server User model through RESTful approach.
Warm up…
This follow-up article is much shorter than the previous post because it reuses certain solutions from there.
We are:
- Reusing controller from either the previous article or from the Yii 2 Guide, only modified to work correctly in multi-application of the Yii 2 Advanced Project Template
- Using existing User model because in this template it is connected to database so works correctly
The controller
Add the controller from the guide or the previous post and only change paths to use User model that is stored in common folder/namespace:
<?php namespace frontend\controllers; use yii\rest\ActiveController; class UserController extends ActiveController { public $modelClass = 'common\models\User'; }
Put it to controllers subfolder in frontend folder/app under UserController.php file name.
Testing
Since we’re using an extra controller in the frontend app, we need to execute following URL to test our solution:
http://localhost/yii-advanced/frontend/web/index.php?r=user
If everything is OK, you should see a response (list of users) in either XML format:
Or in JSON (default) format — depending on what format your calling client requests:
As you can see, it throws out everything you have in your model, including (in this case) all the sensitive security data which is not what we want to achieve. So, you should head up directly to RESTful Web Applications: Resources guide page in order to implement filtering this out.