About RESTful-API
polinwei opened this issue · comments
Hi Sir:
If I want to add a RESTful-API for blog , Which directory is better to put? like 'api\modules\v1\controllers'.
Is there anything to pay attention to?
Hello!
You can use the analogy of User api.
'api\modules\v1\controllerlers\BlogController.php'.
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
You can do in by analogy the backend, as an example:
https://github.com/Dominus77/yii2-advanced-start/tree/api_module_dev
Api is made for the users module
References for access:
http://mysite.com/api/users
http://mysite.com/api/user/1
Basic moments:
- In Modules.php we add a variable $isApi
- Let's add switching of controllers
yii2-advanced-start/modules/users/Module.php
Lines 58 to 60 in a6514a0
- In the api config we connect the module as in the backend
yii2-advanced-start/api/config/main.php
Lines 25 to 27 in a6514a0
- In the same place we connect BootstrapApi.php
yii2-advanced-start/api/config/main.php
Lines 13 to 16 in a6514a0
- Add the api folder and Controller DefaultController.php to the Users controllers.
https://github.com/Dominus77/yii2-advanced-start/blob/api_module_dev/modules/users/controllers/api/DefaultController.php - Let's add a model for api
https://github.com/Dominus77/yii2-advanced-start/blob/api_module_dev/modules/users/models/api/User.php - Add the file BootstrapApi.php which was connected to api/config/main.php
https://github.com/Dominus77/yii2-advanced-start/blob/api_module_dev/modules/users/BootstrapApi.php
Now for Users RESTful is available:
http://yii2-advanced-start.loc/api/users // All users
http://yii2-advanced-start.loc/api/user/1 // User with ID=1
Since we have not disabled the old api in the config, it is also available:
http://yii2-advanced-start.loc/api/v1/users // All users
http://yii2-advanced-start.loc/api/v1/users/1 // User with ID=1
By this principle, you can add api to other modules.
Hi Sir:
Thanks. It is helpful. I will try it.
Why is the value 'controller' => [ 'users/default']
in BootstrapApi.php ?
I think I have fully understand. I also finished the REST for blog. Thanks for your detail document.
Why is the value 'controller' => [ 'users/default'] in BootstrapApi.php ?
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html#configuring-url-rules