Not long ago to do a project, is to use the YII2 framework to write a restful style of API, went to the next "YII 2.0 authoritative Guide", found that the above is written relatively brief. So just write a tutorial post here to help you get started quickly with a small partner who has just come into contact with YII2 framework restful.
I. Directory structure
The implementation of a simple RESTful API requires only three files. The directory is as follows:
Frontend ├─config │ └main.php ├─controllers │ └bookcontroller.php └─models └ book.php
Second, configure the URL rules
1. Modify the server's rewrite rule to point all URLs to index.php to support the/BOOKS/1 format.
If it is an Apache server, create a new. htaccess file in the frontend/web/directory. The contents of the file are as follows:
Rewriteengine on# If A directory or a file exists, use the request directly Rewritecond%{request_filename}!-f Re Writecond%{request_filename}!-d# Otherwise forward the REQUEST to index.php rewriterule . index.php
If it is an nginx server, modify nginx/conf/nginx.conf to add the following red tag content in the "location/{}" of the current "server{}":
Location/{try_files $uri $uri//index.php$is_args$args;}
2. Modify the frontend/config/main.php file to add a URL rule for the book controller. In this way, the data can be accessed and manipulated through a glorified URL and meaningful HTTP verbs. The configuration is as follows:
' Components ' = [ ' urlmanager ' + [' enableprettyurl ' = ' = ', ' enablestrictparsing ' and ' = true,< c3/> ' Showscriptname ' + false, ' rules ' = [ [' class ' = ' Yii\rest\urlrule ', ' controller ' + ' book '] , ], ],],
Third, create a model
1. Create a book table in the database. The contents of the Book table are as follows:
--------------------------------table structure------------------------------DROP table IF EXISTS ' book '; CREATE TABLE ' book ' ( ' id ' int ($) unsigned NOT NULL auto_increment, ' name ' char (a) ' NOT null DEFAULT ' ', ' num ' tinyint (3) unsigned not NULL default ' 0 ', PRIMARY KEY (' id ')) engine=innodb auto_increment=6 default charset=utf8;-- ------------------------------Records of book------------------------------INSERT to ' book ' VALUES (' 1 ', ' TOEFL ', ' 1 0 '); insert INTO ' book ' Values (' 2 ', ' ielts ', ' ' + '); insert INTO ' book ' Values (' 3 ', ' sat ', ' + '); insert INTO ' book ' Values (' 4 ', ' GRE ', ' + '); INSERT into ' book ' VALUES (' 5 ', ' GMAT ', ' 50 ');
2. Create a new book.php in the frontend/models/directory. The contents of the file are as follows:
Namespace Frontend\models;use yii\db\activerecord;class Book extends activerecord{public static function TableName () { return ' book '; }}
Iv. Creating a Controller
Create a new bookcontroller.php in the frontend/controllers/directory. The controller class extends from Yii\rest\activecontroller. By specifying Yii\rest\activecontroller::modelclass as the Frontend\models\book, the controller can know which model to use to acquire and manipulate the data. The contents of the file are as follows:
Namespace Frontend\controllers;use yii\rest\activecontroller;class Bookcontroller extends activecontroller{ Public $modelClass = ' Frontend\models\book ';}
V. Testing
Here we have finished creating RESTful-style APIs for accessing user data. The APIs created include:
Get/books: List all books Head/books: A summary of the list of displayed books Post/books: Added 1 books get/books/1: Return to book id=1 details HEAD/BOOKS/1: Display book id=1 overview information Patch/ BOOKS/1 and PUT/BOOKS/1: More book id=1 info delete/books/1: Delete book id=1 info options/books: Show verbs about end/books support OPTIONS/BOOKS/1: Show about End Verbs supported by/BOOKS/1
You can access the API by entering the URL Http://{frontend's domain name}/books in your Web browser, or by using some browser plugins to send specific headers requests, such as Firefox restclient, Chrome's Advanced Rest Client, Postman, and more.
Vi. description
1.Yii the name of the controller to be used at the end automatically becomes the plural. This is because the yii\rest\urlrule can be used for their end-automatic complex controller. You can disable this behavior by setting Yii\rest\urlrule::p luralize to False:
' Rules ' = [ ' class ' = ' Yii\rest\urlrule ', ' controller ' = ' book ', ' Pluralize ' and false],
2. You can use the fields and expand parameters to specify which field should be included within the result. For example, the name of the URL Http://{frontend}/books?fields=name,num will return only the name and Num fields.
Next: YII2 Framework RESTful API Tutorial (ii)-formatted response, authorization authentication and rate limiting
Yii2 Framework RESTful API Tutorial (i)-Quick Start