Home  >  Article  >  Backend Development  >  Quick start tutorial for making RESTful style API with Yii2 framework

Quick start tutorial for making RESTful style API with Yii2 framework

高洛峰
高洛峰Original
2017-01-09 11:18:061169browse

Let me first tell you what REST is

restful

REST’s full name is Representational State Transfer, which in Chinese means representational (Editor’s note: usually translated as representation) state transfer . It first appeared in 2000 in the doctoral thesis of Roy Fielding, one of the primary writers of the HTTP specification. He mentioned in the paper: "The purpose of writing this article is to understand and evaluate the architectural design of network-based application software on the premise of complying with the architectural principles, and to obtain an architecture with strong functions, good performance, and suitable for communication. Architecture. REST refers to a set of architectural constraints and principles. "If an architecture conforms to the constraints and principles of REST, we call it a RESTful architecture.

REST itself does not create new technologies, components or services, but the idea behind RESTful is to use the existing features and capabilities of the Web and make better use of some of the existing Web standards. guidelines and constraints. Although REST itself is deeply influenced by Web technology, theoretically the REST architectural style is not bound to HTTP, but currently HTTP is the only instance related to REST. So the REST we describe here is also REST implemented through HTTP.

I was working on a project not long ago, which was to use the Yii2 framework to write a set of RESTful-style APIs. I checked the "Yii 2.0 Authoritative Guide" and found that it was written relatively briefly. So I am writing a tutorial post here, hoping to help friends who are new to Yii2 framework RESTful get started quickly.

1. Directory structure

Only three files are needed to implement a simple RESTful API. The directory is as follows:

frontend
├─ config
│ └ main.php
├─ controllers
│ └ BookController.php
└─ models
└ Book.php

2. Configure URL rules

1. Modify the rewrite rules of the server and point all URLs to index.php , making it support the /books/1 format.

If it is an Apache server, create a new .htaccess file in the frontend/web/ directory. The content of the file is as follows:

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

If it is an Nginx server, modify nginx/conf/nginx.conf and set it in the "location / {} of the current "server{}" "Add the following red mark content:

location / {
  try_files $uri $uri/ /index.php$is_args$args;
}

2. Modify the frontend/config/main.php file and add a URL rule for the book controller. This way, data can be accessed and manipulated through pretty URLs and meaningful http verbs. The configuration is as follows:

'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'book'],
],
],
],

3. Create a model

1. Create a book table in the database. The contents of the book table are as follows:

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` char(50) 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 INTO `book` VALUES ('1', 'toefl', '10');
INSERT INTO `book` VALUES ('2', 'ielts', '20');
INSERT INTO `book` VALUES ('3', 'sat', '30');
INSERT INTO `book` VALUES ('4', 'gre', '40');
INSERT INTO `book` VALUES ('5', 'gmat', '50');

2. Create a new Book.php in the frontend/models/ directory. The content of the file is as follows:

namespace frontend\models;
use yii\db\ActiveRecord;
class Book extends ActiveRecord
{
public static function tableName()
{
return 'book';
}
}

4. Create 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 frontend\models\Book, the controller knows which model to use to obtain and process data. The content of the file is as follows:

namespace frontend\controllers;
use yii\rest\ActiveController;
class BookController extends ActiveController
{
public $modelClass = 'frontend\models\Book';
}

5. Test

At this point, we have completed the creation of a RESTful style for accessing user data API. The created API includes:

GET /books: List all books
HEAD /books: Display summary information of the book list
POST /books: Add 1 new book
GET /books/1: Return detailed information of book ID=1
HEAD /books/1: Display summary information of book ID=1
PATCH /books/1 and PUT /books/1: Update book ID=1 Information
DELETE /books/1: Delete information about book ID=1
OPTIONS /books: Show support for verbs about end /books
OPTIONS /books/1: Show support for end /books/1 The verb

can be accessed by entering the URL http://{frontend's domain name}/books in a web browser, or using some browser plug-ins to send specific headers requests, such as Firefox's RestClient, Chrome Advanced Rest Client, postman, etc.

6. Instructions

1.Yii will automatically pluralize the name of the controller used at the end. This is because yii\rest\UrlRule automatically pluralizes controllers for the endpoints they use. This behavior can be disabled by setting yii\rest\UrlRule::pluralize to false:

'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'book', 'pluralize' => false],
],

2. You can use the fields and expand parameters to specify which fields should be included within the results. For example: URL http://{frontend's domain name}/books?fields=name,num will only return the name and num fields.

The above is the quick start tutorial for making RESTful API with Yii2 framework introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. of. I would also like to thank you all for your support of the PHP Chinese website!

For more articles related to Yii2 framework’s RESTful-style API quick-start tutorial, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn