incorporate a REST API into existing Yii2 project


I have an existing Yii2 (basic template) application. We are looking to now build an API to allow communication between another non-Yii system. So I’m thinking along the lines of a REST API. What would be the best way/process to integrate whilst maintaining DRY principles.

I was thinking along the lines of create a new module to house the restful api and go from there. Is that a reasonable standard idea or is there a better way???

Finally, in this situation we need to enable authentication. Would I need to create a new RESTful USER controller within this module, or should I be making the web application USER controller restful? If so, how would that effect the web application itself? :unsure:

[color="#006400"]/* moved to REST (no pun intented) */[/color]

In my opinion the best way is creating new controllers with own namespace like app\controllers\api\* and cover the models inside.

I managed with some help to get this going. I had a little query around organization. How should I be managing the code in this arrangement. For instance I tried to set the fields in my app\modules\api\controllers\UserController and it didn’t work, so I set it in my app\models\User.php and it worked. I realize as I write this the docs reference Model not controller.

But, as my REST API is a module, should I be looking to create a User model within my module that extends from the app\models\User and override fields that way, thus keeping all the REST details in one place. Or should I just be adding all this REST based code to my existing app\models\User model?

+1 for the pun! :lol:


I’ve used this tutorial

"Setup RESTful API in Yii2" from budiirawan dot com