Application of API in Yii2 restful and detailed _php example

Source: Internet
Author: User
Tags error handling new set yii advantage

What is the RESTful style API

For a variety of client devices and server-side communication, we often use APIs to provide data to the client, providing some kind of resources. On the concept of restful, a check a big push, one or two sentence also explain unclear, let us first according to our popular understanding: In many styles, many of the principles of the API, restful is a set of relatively excellent interface to call the way.

Yii2 How to implement restful-style APIs

1, the establishment of a separate application

In order to increase the maintainability of the program, easy to operate, we choose to create a new set of applications, which is also for the foreground and the background of the application area separately. Some people are going to yell, why do they have to do it alone? If you simply provide a few individual H5 pages, it is not necessary, but the fact is often the client to upgrade Ah, to add a different version Ah, this requires us not only to the backend to add a separate set of applications, we have to add a variety of versions to control.

In the peer directory of the Web front-end (frontend) and back-end (backend), create a new folder, naming API, whose directory structure looks like this:

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

It can be seen that the directory structure is basically the same as the backend no other difference, because we are copying the backend project, only partial optimization.

2, beautify the route for the new API application

First of all, make sure your Web server opens the rewrite rule, we don't say the details, but that's the premise.

Then configure the api/config/main.php file

' Components ' => [
//other config
' Urlmanager ' => [
' Enableprettyurl ' => true,
' Showscriptname ' => false,
' enablestrictparsing ' =>true,
' rules ' => [],
]
],

Finally, you only need to add the. htaccess file at the application entry level, so let's take Apache for example.

Options +followsymlinks
indexignore */*
rewriteengine
on # If a directory or a file exists, use it directly
Rewritecond%{request_filename}!-f
Rewritecond%{request_filename}!-d
# Otherwise forward it to index.php rewriterule
. index.php
Rewriterule \.svn\//404.html
rewriterule \.git\//404.html

3. Use GII to generate test modules

With a handy demo, we create a new Datasheet goods table and insert a few data into it.

CREATE TABLE ' goods ' (
' id ' int (one) not null auto_increment,
' name ' varchar ' (MB) 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'll take advantage of the GII to build the modules and take advantage of the GII module to generate goods information in the following figure

Now, our API directory structure should be several of the following directories

│
├─models
│goods.php
│
├─modules
│└─v1
││module.php
││ │├─controllers
││defaultcontroller.php
││goodscontroller.php
││
│└─views
│└─default
│index.php

4. Reconfigure the Controller

In order to implement the RESTful-style API, in Yii2, we need to rewrite the controller

<?php
namespace 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 operation

After a few steps, we have successfully created an API that satisfies the restful style for goods. For better and more convenient demos, we use tool postman to simulate requests.

To witness our operation, we use postman to ask Get/v1/goods to see how the results are:

As you can see from the screenshot above, Get/v1/goods has been able to easily get the data from our table.

Of course, YII2 also encapsulates the following actions for the API:

Get/users: List all users by page
Head/users: Displays a summary of the user list
Post/users: Create a new user
Get/users/123: Back to user 123 for more information
Head/users/123: Displays overview information for user 123
Patch/users/123 and put/users/123: Update user 123
delete/users/123: Delete User 123
Options/users: Displays verbs about end/users support
Options/users/123: Displays verbs about end/users/123 support

If not, we can use postman to send a POST request to/v1/goods, we will find that a new product has been created successfully.

You need to be reminded that the operation is also careful and note:

If your controller end is not a plural (for example, blog blogs) Please ensure that the request is a plural! This is because in the restful architecture, the URL can only have nouns but not verbs, nouns are often relative to the data table, the data table is a "set", so the noun is often the form of plural.

7, about the authorization certification

Why do I need to authorize certification? This is required in general operations. For example, users want to set their own information.

In order to make the YII2 restful certification more clear, we will be in two two different ways to explain.

First you need to turn on authentication:

Let's say we've created the datasheet user with the field Access-token in step 3rd, and we've built the corresponding model and controller on GII

Configuring main.php Files

' Components ' => ['
user ' => [ 
' Identityclass ' => ' common\models\user ',
' Enableautologin ' => True,
' enablesession ' =>false
],
],

Configure authenticator behavior for the controller Specify authentication method

<?php
namespace 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 also need to implement the Findidentitybyaccesstoken method in Identityclass

The public static function Findidentitybyaccesstoken ($token, $type = null)
{return
static::findone ([' Access_ Token ' => $token, ' status ' => self::status_active]);
}

In this way, we first look at the results through postman simulations without access-token requests.

{
"name": "Unauthorized", "Message
": "Your are requesting with a invalid credential.", "
Code": 0,
" Status ': 401, '
type ': ' Yii\\web\\unauthorizedhttpexception '
}

Tip 401 We don't have access!

We carry the correct access-token on the requested link, the controller will continue to perform other checks (frequency limit, operation rights, etc.) before it can return the correct user information.

Need to be reminded that: through the form of a URL to Access-token transmission there is a certain risk, there may be a leak of data! Generally speaking, access-token need to be put into HTTP headers for delivery! Unless the client's request is in JSONP format!

8. Rate Limit

Rate limit, the operation is entirely for security reasons, we need to limit the same interface for a period of time too many requests.

The rate limit is not enabled by default, and Yii\web\user::identityclass should implement yii\filters\ratelimitinterface with the enable rate limit, which means our common\models\ User.php need to implement the Yii\filters\ratelimitinterface interface three methods, the specific code can refer to:

Use Yii\filters\ratelimitinterface;
Use Yii\web\identityinterface;
Class User extends ActiveRecord implements Identityinterface, Ratelimitinterface
{
//other code ... 
Returns the maximum number of requests allowed at a given time, such as setting up to 5 requests in 10 seconds (small numbers for us to simulate testing) public
function Getratelimit ($request, $action) {return 
[5, ]; 
}
Back to the remaining allowed requests and the corresponding number of Unix timestamps when the last rate limit check, the public
function loadallowance ($request, $action) {return 
[$this-> Allowance, $this->allowance_updated_at]; 
} 
Saves the number of requests remaining and the current UNIX timestamp public
function saveallowance ($request, $action, $allowance, $timestamp) { 
$this- >allowance = $allowance; 
$this->allowance_updated_at = $timestamp; 
$this->save (); 
} 

Be aware that you still need to add two new fields to the datasheet user

Allowance: Number of remaining allowed requests

ALLOWANCE_UPDATED_AT: The corresponding number of Unix timestamps

After we have enabled the rate limit, Yii automatically uses Yii\filters\ratelimiter to configure a behavior filter for Yii\rest\controller to perform a rate limit check.

Now we have to look at the results through postman request V1/users, we will find that in 10 seconds to call the API interface more than 5 times, we will get a state of more than 429 requests for exception information.

{
' name ': ' Too Many Requests ',
' message ': ' Rate limit exceeded. ',
' code ': 0,
' status ': 429,
' type ' : "Yii\\web\\toomanyrequestshttpexception"
}

9, about the version

In order to be compatible with the historical version and consider backwards compatibility, we implemented the version as a URL at the beginning of the operation, and this is no longer explained here.

10. Error Handling

The HTTP status code for the rest framework of YII can be referenced as follows.

200:ok. Everything's fine.
201: A resource was successfully created in response to a POST request. The Location header contains a URL that points to the newly created resource.
204: The request was processed successfully and the response does not contain body content (similar to DELETE request).
304: The resource has not been modified. You can use a cached version.
400: the wrong request. May be caused by a variety of user reasons, such as invalid JSON data in the request, invalid operation parameters, and so on.
401: Validation failed.
403: Authenticated users are not allowed access to the specified API end.
404: The requested resource does not exist.
405: The method not permitted. Please check the HTTP methods allowed by the Allow header.
415: Unsupported media type. The requested content type or version number is invalid.
422: Data validation fails (for example, in response to a POST request). Please check for detailed error messages in the response body.
429: Too many requests. Because the speed limit request was denied.
500: Internal server error. This may be caused by an internal program error.

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.