Detailed use of yii2 RESTful api, yii2restful

Source: Internet
Author: User

Detailed use of yii2 RESTful api, yii2restful

What is a RESTful API?

For communication between various client devices and the server, we often use APIs to provide data and resources for the client. Regarding the concept of RESTful, one or two statements cannot be clearly explained. Let's first follow our common understanding: In APIs with many styles and principles, RESTful is a set of excellent interface calling methods.

How to Implement RESTful APIs in Yii2

1. Create a separate application

In order to increase the maintainability and operability of the program, we choose to create a new application, which is also to be operated separately from the foreground application and background application. Some people are clamoring. Why do we have to create a separate set? If you simply provide a few h5 pages, there is no need, but the fact is that the client needs to be upgraded and different versions need to be added, in this case, we need not only to add a separate set of applications to the backend, but also to add various versions for control.

Create a folder named api in the same directory as the WEB Front-end (frontend) and backend (backend). The directory structure is as follows:

├─assets│      AppAsset.php├─config│      bootstrap.php│      main-local.php│      main.php│      params-local.php│      params.php├─runtime└─web    │ index.php    ├─assets    └─css

It can be seen that the directory structure is basically the same as that of backend, because we just copied the backend project and only partially optimized it.

2. Beautify the route for the newly created api application

First, ensure that your web server enables rewrite rules. We will not talk about the details, but this is the premise.

Configure the api/config/main. php file

'components' => [    // other config    'urlManager' => [        'enablePrettyUrl' => true,        'showScriptName' => false,        'enableStrictParsing' =>true,        'rules' => [],    ]],

At last, you only need to add the. htaccess file at the same level in the application portal. We use apache as an example.

Options +FollowSymLinksIndexIgnore */*RewriteEngine on# if a directory or a file exists, use it directlyRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d# otherwise forward it to index.phpRewriteRule . index.phpRewriteRule \.svn\/  /404.htmlRewriteRule \.git\/  /404.html

3. Use gii to Generate Test modules

We created a new table named goods and inserted several data records into it.

CREATE TABLE `goods` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `name` varchar(100) NOT NULL DEFAULT '',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `goods` VALUES ('1', '11111');INSERT INTO `goods` VALUES ('2', '22222');INSERT INTO `goods` VALUES ('3', '333');INSERT INTO `goods` VALUES ('4', '444');INSERT INTO `goods` VALUES ('5', '555');

Then we use gii to generate modules, and then use the gii module to generate goods information according

Now, our api directory structure should contain the following directories:

│├─models│      Goods.php│├─modules│  └─v1│      │  Module.php│      ││      ├─controllers│      │      DefaultController.php│      │      GoodsController.php│      ││      └─views│          └─default│                  index.php

4. reconfigure the controller.

To implement restful APIs, We need to rewrite the Controller in yii2.

<?php@see http://www.manks.top/yii2_restful_api.htmlnamespace api\modules\v1\controllers;use yii\rest\ActiveController;class GoodsController extends ActiveController{    public $modelClass = 'api\models\Goods';}

5. Configure Url rules for Goods

'rules' => [    [        'class' => 'yii\rest\UrlRule',        'controller' => ['v1/goods']    ],]

6. Simulate request operations

After the above steps, we have successfully created a restful api for goods. For better and more convenient demonstration, we use the postman tool to simulate requests.

To witness our operations, we use postman to request GET/v1/goods to see how the results are:

We can clearly see from the above that GET/v1/goods can easily obtain the data in our table.

Yii2 also encapsulates the following operations on this api:

  • GET/users: list all users page by page
  • HEAD/users: displays the overview of the user list
  • POST/users: Create a new user
  • GET/users/123: detailed information of user 123 is returned.
  • HEAD/users/123: displays the overview of user 123.
  • PATCH/users/123 and PUT/users/123: update user 123
  • DELETE/users/123: DELETE user 123
  • OPTIONS/users: displays the verbs supported by the end/users.
  • OPTIONS/users/123: displays the verbs supported by end/users/123.

If you don't believe it, you can use postman to send a post request to/v1/goods. We will find that a new product is successfully created.

Note:

If the end of your controller is not a plural number (for example, a blog is not a blogs), make sure that the request is a plural number! This is because in a RESTful architecture, a website can only contain nouns but cannot contain verbs. nouns often correspond to data tables. A data table is also a "set ", therefore, this term is often in the form of a plural number.

7. Authorization Authentication

Why do I need authorization? This is required in general operations. For example, you need to set your own information.

To make it clearer about yii2 restful authorization, we will describe two different methods.

First, you must enable authentication:

Assume that we have created a user table containing the access-token field in step 1, and created the corresponding model and controller using gii.

Configure the main. php file

'components' => [    'user' => [         'identityClass' => 'common\models\User',        'enableAutoLogin' => true,        'enableSession'=>false    ],],

Specify the authentication method for the authenticator action configured for the controller.

<?php@see http://www.manks.top/yii2_restful_api.htmlnamespace api\modules\v1\controllers;use yii\rest\ActiveController;use yii\helpers\ArrayHelper;use yii\filters\auth\QueryParamAuth;class UserController extends ActiveController{    public $modelClass = 'api\models\User';    public function behaviors() {        return ArrayHelper::merge (parent::behaviors(), [                 'authenticator' => [                     'class' => QueryParamAuth::className()                 ]         ] );    }}

Finally, we need to implement the findIdentityByAccessToken method in identityClass.

public static function findIdentityByAccessToken($token, $type = null){    return static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]);}

In this way, we first use postman to simulate a request without access-token to view the result.

{  "name": "Unauthorized",  "message": "You are requesting with an invalid credential.",  "code": 0,  "status": 401,  "type": "yii\\web\\UnauthorizedHttpException"}

Prompt 401 we do not have permission to access!

We carry the correct access-token on the request link. After the authentication is passed, the Controller will continue to perform other checks (frequency limit, Operation permission, etc ), to return the correct user information.

It should be noted that there is a certain risk of access-token transmission through url, which may cause data leakage! Generally, the access-token must be placed in the HTTP header for transmission! Unless the client request is in jsonp format!

[Considering that most of the articles collected on Chinese websites are very frequent at present, the author does not specify the source of the original article. The original author prefers the readers to check the original article to avoid updating all the articles due to any problems and avoid misleading.]

View Original

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.