Yii2 starts the Restful style API interface, which is used for front-end and back-end separation projects or external third-party API interfaces.

Use advanced Yii2 template: yii2-app-advanced

Reason: Establishing Restful’s Api is equivalent to an independent project, such as backend (backend) and frontend (frontend). Because the Api and the backend project are familiar with each other, only the encapsulation method is exposed to the outside world, so you need to copy the backend and re- Name it api project, place it in the root directory, and have the same level as backend, frontend, common, etc.

1. Preparation

?1. Download and install integration tools, such as wampServer, phpStudy, etc., which integrate php, apache, mysql and other environments. I use wampServer, 7.xphp,

?2. Mysql access address: http://localhost/phpmyadmin/, account: root, password is blank, no need to fill it in

?3. If you use the default access directory www of wampServer, the project will be downloaded to this directory;

3.1. If you customize the location of the project, you need to set the httpd-hosts.conf file of apache. The location is: D:\wamp64\bin\apache\apache2.4.37\conf\extra, add configuration

<VirtualHost *:80>
   ServerName api.appadvanced.dev
    DocumentRoot "E:/my_advanced/api/web/"
   <Directory "E:/my_advanced/api/web/">
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule.index.php

# use index.php as index file
DirectoryIndex index.php
AllowOverride All
Require local
   </Directory>
</VirtualHost>

<VirtualHost *:80>
   ServerName appadvancedbackend.dev
ServerAlias *.appadvancedbackend.dev
   DocumentRoot "E:/my_advanced/backend/web"
   <Directory "E:/my_advanced/backend/web">
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule.index.php

DirectoryIndex index.php
AllowOverride All
Require local

   </Directory>
</VirtualHost>

?3.2. You need to set up the system’s hosts file. Location: C:\Windows\System32\drivers\etc\hosts. If it cannot be seen, it is hidden. Open the folder and select View, and check the hidden items.

127.0.0.1 api.appadvanced.dev
127.0.0.1 appadvancedfrontend.dev

?3.3. At this point, the access address of the api project is set: api.appadvanced.dev, and the access address of the background backend: appadvancedbackend.dev

2. Install Yii2.0

Install via composer

1. This is the preferred method to install Yii2.0. If you have not installed composer, you can go here to download composer-Setup.exe to install it.

2. After installing composer, verify whether the installation is successful and enter composer in cmd

composer

If the picture appears, it means the installation is successful.

3. Run the following command to install the composer Asset plug-in:

// It is recommended to use domestic images before installation. I use Alibaba Cloud.
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer

// Check whether the global image installation is successful
composer config -l -g

composer global require "fxp/composer-asset-plugin:^1.2.0"
// or
php composer.phar global require "fxp/composer-asset-plugin:^1.2.0"

4. Install the advanced application template and run the following command:

composer create-project yiisoft/yii2-app-advanced my_advanced
// or
php composer.phar create-project yiisoft/yii2-app-advanced my_advanced

5. Initialize the advanced template and install the dependencies after initialization. The dependency files are in the vendor

cd my_advanced
init
//Select 0 Development development mode, then select yes, and finally generate some configuration files

Note: Because the dependency requires access to foreign countries, installation often fails, please try more installations

// Enter the root directory and install instructions
composer update
// or
composer install

6. If you can access it normally, you can

// The backend access directory, the customized configuration is directly assigned to the web directory, and the default access is index.php
http://appadvancedbackend?r=site/index

// This link is installed in the www directory of wampServer by default
http://localhost/basic/web/index.php?r=site/index

7. Modify database connection

Open common\config\main-local.php, local configuration database connection information

'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=127.0.0.1;dbname=yii2advanced',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8',
        ],

Note: About the project configuration item coverage issue here

8. Execute migrate database migration in the root directory to generate user data table

yii migrate

9. Copythe backend directory and name it api

Open api\config\main.php and modify id, controllerNamespace:

return [
    'id' => 'app-api',
    'basePath' => dirname(__DIR__),
    'controllerNamespace' => 'api\controllers',
]

10. Open common\config\bootstrap.php and add the following aliases

Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');

11. The path of the API project that has been configured in the preparation work can be accessed directly.

//Api access directory, the customized configuration is directly assigned to the web directory, and index.php is accessed by default
http://api.appadvanced.dev?r=site/index

3. Why create a separate API application

Create an API application separately to facilitate maintenance and avoid the following problems

  • Configuration conflict
  • Controller naming is inconvenient
  • URL beautification rule conflict
  • The division of labor is clear. frontend is the frontend directory; backend is the backend directory; api is the api directory.

1. Open api\controllers and create a new User controller, inherit from yii\rest\ActiveController and name it UserController. The code is as follows:

<?php
namespace api\controllers;
use yii\rest\ActiveController;

class UserController extend extends ActiveController
{
    public $modelClass = 'common\models\User';
    
}

Here create a user controller that inherits yii\rest\ActiveController and specify the model to be operated on

2. Enable JSON input

Configure the request application component’s parsers property to use yii\web\JsonParser for JSON input

Open the configuration file api\config\main-local.php and modify it to the following code:

<?php

$config = [
    'components' => [
        'request' => [
            ...
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',

            ],
            ...
        ],
    ],
];
...

3. Configure URL rules

Add URL beautification rules to the user controller just now, open api\config\main.php, modify the components attribute, and add the following code:

...
'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [ // You don't need to set rules if there are no special requirements
        ['class' => 'yii\rest\UrlRule',
        'controller' => 'user'
        ],
    ],
]

...

ok, now it becomes an API that conforms to the RESTful style.
It seems that nothing is written in the controller, it just specifies a model, but it has completed a lot of functions behind the scenes. The list is as follows:

  • GET /users: List all users page by page
  • HEAD /users: Displays summary information of the user list
  • POST /users: Create a new user
  • GET /users/123: Returns the details of user 123
  • HEAD /users/123: Displays summary information of user 123
  • PATCH /users/123: and PUT /users/123: Update user 123
  • DELETE /users/123: Delete user 123
  • OPTIONS /users: Displays supported verbs for end /users
  • OPTIONS /users/123: Shows supported verbs for end /users/123

4. How to access

1. In cmd, you can use the curl command to access, the command is as follows:

curl -i -H "Accept:application/json" "http://api.appadvanced.dev/users"

The command line is still troublesome and inconvenient for testing. It is recommended to use postman, apifox and other testing tools. You can also use the web version of the interface testing tool.

2. You may have found that s, users are added when accessing any routing address. Why? Resources, you need to understand The word resource, since it is a collection, must be a collection, there must be a lot of them, so it must be added in the plural. This is how I understand it.

You said that I just don’t want to add s, and I just want to use http://api.appadvanced.dev/user for access. Okay, that’s fine. Satisfies you, just not recommended

Continue to open the configuration file api\config\main.php and modify the urlManager just added as follows:

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [ // You don't need to set rules if there are no special requirements
        ['class' => 'yii\rest\UrlRule',
        'controller' => 'user',
        'pluralize' => false, //Set to false to remove the plural form
        ],
        // Method 1: Link to a specific domain name http://youlocal.com/vueadmin/sys-menu/2/menu-ids, get parameter id
        '/vueadmin/sys-menu/<id:\d + >/menu-ids' => '/vueadmin/sys-menu/menu-ids/',
        //Method 2: Links to specific domain names
        //[
        // 'pattern' => '/vueadmin/sys-menu/<id:\d + >/menu-ids',
        // 'route' => '/vueadmin/sys-menu/menu-ids',
        // 'defaults' => [ 'id' => 1 ], // Default 1
        // ]
    ],
]

Adding 'pluralize' => false, means removing the plural form, again not recommended

Ok, we didn’t write any code in the controller, it generated many methods for us, but sometimes we may need to modify some codes to achieve the effect we want, such as querying join tables and then returning data.

3. Next we will implement this function:

Open the newly created user controller and rewrite the action method:

<?php

namespace api\controllers;
use yii\rest\ActiveController;

class UserController extend extends ActiveController
{
    public $modelClass = 'common\models\User';
    
    public function actions()
    {
        $action= parent::actions(); // TODO: Change the autogenerated stub, hide the original method of ActiveController so that the method can be rewritten
        unset($action['index']);
        unset($action['create']);
        unset($action['update']);
        unset($action['delete']);
    }
    
    public function actionIndex()
    {
        //your code
    }
    
}

This way we can rewrite his code. Ha ha

4. Let’s create a new action of our own

<?php

namespace api\controllers;
use yii\rest\ActiveController;

class UserController extend extends ActiveController
{
    public $modelClass = 'common\models\User';
    
    public function actions()
    {
        $action= parent::actions(); // TODO: Change the autogenerated stub
        unset($action['index']);
        unset($action['create']);
        unset($action['update']);
        unset($action['delete']);
    }
    
    public function actionIndex()
    {
        //your code
    }
    
    public function actionSendEmail() //If it is a get request
    {
        //Business logic
    }
    
}

5. Modify api\config\main.php

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [ // You don't need to set rules if there are no special requirements
        [
            'class' => 'yii\rest\UrlRule',
            'controller' => 'user',
            //'pluralize' => false, //Set to false to remove the plural form
            'extraPatterns'=>[ // Configure the corresponding url /send-email. If you want to search, you can configure GET search here
                'GET send-email'=>'send-email'
            ],
        ],
        // Method 1: Link to a specific domain name http://youlocal.com/vueadmin/sys-menu/2/menu-ids, get parameter id
        '/vueadmin/sys-menu/<id:\d + >/menu-ids' => '/vueadmin/sys-menu/menu-ids/',
        //Method 2: Links to specific domain names
        //[
        // 'pattern' => '/vueadmin/sys-menu/<id:\d + >/menu-ids',
        // 'route' => '/vueadmin/sys-menu/menu-ids',
        // 'defaults' => [ 'id' => 1 ], // Default 1
        // ]
    ],
]

Then try to visit http://api.appadvanced.dev/users/send-email

ps: Any action you write yourself must be configured in extraPatterns

6. Customize the format of response return,

If there is an error throw other than 200, but the front end wants the correct response format, the code is still 200, but both the error code and msg will be responded. At this time, you need to modify the config

Modify api\config\main.php and add the following code in components:

'response' => [
            'class' => 'yii\web\Response',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                $response->data = [
                    'success' => $response->isSuccessful,
                    'code' => $response->getStatusCode(),
                    'message' => $response->statusText,
                    'data' => $response->data,
                ];
                $response->statusCode = 200;
            },
        ],

200 is used here to express uniformly. Of course, not all are 200, such as code = 0;