Dominus77 / yii2-advanced-start

Yii2 Start Project Advanced Template

Home Page:https://dominus77.github.io/yii2-advanced-start/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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:

  1. In Modules.php we add a variable $isApi
  2. Let's add switching of controllers
    } else if($this->isApi === true) {
    $this->controllerNamespace = 'modules\users\controllers\api';
    } else {
  3. In the api config we connect the module as in the backend
    'users' => [
    'isApi' => true,
    ],
  4. In the same place we connect BootstrapApi.php
    'bootstrap' => [
    'log',
    'modules\users\BootstrapApi',
    ],
  5. 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
  6. Let's add a model for api
    https://github.com/Dominus77/yii2-advanced-start/blob/api_module_dev/modules/users/models/api/User.php
  7. 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