Creating Web Service

Now that prepartions done we’ll start with service part of our application using high performance Yii 2.0 PHP framework.
It’s a great fit since it has built in functionality that allows kickstarting with RESTful APIs easily. Basics are already
done for you ensuring many details to be set up correctly while more advanced things could be implemented as needed.

Create Database Structure

We’ll use database named angular_spa so create it. Then add book table with following structure:

Create Web Service - 图1

You can use angular_spa.sql in order to import it.

Insert some data in the table, you can create more tables but for the sake of simplicity, in this tutorial we’ll use
only book.

Configure Database Connection

Open config/db.php in the root of Yii web service application. Modify db configuration
to specify your MySQL settings:

  1. return [
  2. 'class' => 'yii\db\Connection',
  3. 'dsn' => 'mysql:host=localhost;dbname=angular_spa',
  4. 'username' => 'root', // specify your username here
  5. 'password' => '', // specify your password here
  6. 'charset' => 'utf8',
  7. ];

Create Models

Use Gii to generate model class for database tables (we have only one so far).
Refer to Yii’s guide for details on how to do it.

You should get models/Book.php with the following content:

  1. namespace app\models;
  2. use Yii;
  3. class Book extends \yii\db\ActiveRecord
  4. {
  5. public static function tableName()
  6. {
  7. return 'book';
  8. }
  9. public function rules()
  10. {
  11. return [
  12. [['title', 'author', 'publisher', 'year'], 'required'],
  13. [['id', 'year'], 'integer'],
  14. [['title'], 'string', 'max' => 255],
  15. [['description'], 'string'],
  16. [['author','publisher'], 'string', 'max' => 50]
  17. ];
  18. }
  19. }

Set up Yii RESTful Application

If you are not familiar with REST support in Yii 2.0, you can get and idea about it by
reading corresponding guide section.

Create REST Controller

There’s no ability to generate REST CRUD in Yii’s Gii code generator but doing it without it is easy and fun.

First, create BookController.php in the controllers directory.

  1. namespace app\controllers;
  2. use yii\rest\ActiveController;
  3. class BookController extends ActiveController
  4. {
  5. // adjust the model class to match your model
  6. public $modelClass = 'app\models\Book';
  7. public function behaviors()
  8. {
  9. return
  10. \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
  11. 'corsFilter' => [
  12. 'class' => \yii\filters\Cors::className(),
  13. ],
  14. ]);
  15. }
  16. }

The controller class extends from yii\rest\ActiveController. By specifying modelClass as app\models\Book,
the controller knows which model can be used for fetching and manipulating data.

We’re adding CORS behavior in order to grant access to
third party code (AJAX calls from external domain).

If you have more models, create alike controllers for each one.

Configuring URL Rules

Modify application configuration, urlManager component in web.php in the config
directory:

  1. 'urlManager' => [
  2. 'enablePrettyUrl' => true,
  3. 'enableStrictParsing' => true,
  4. 'showScriptName' => false,
  5. 'rules' => [
  6. ['class' => 'yii\rest\UrlRule', 'controller' => 'book'],
  7. ],
  8. ]

The above configuration mainly adds a URL rule for the book controller so that the book data can be accessed and
manipulated with pretty URLs and meaningful HTTP verbs. If you have more controllers, specify them as array:

  1. 'rules' => [
  2. ['class' => 'yii\rest\UrlRule', 'controller' => ['book','user','employee','etc']],
  3. ],

Note: If you are using Apache as a web server, you need to add a .htaccess file to your
web root. In case of nginx you don’t need to do it.

Enable JSON Input

To let the API accept input data in JSON format, configure the parsers property of the request application component
to use the yii\web\JsonParser:

  1. 'request' => [
  2. 'parsers' => [
  3. 'application/json' => 'yii\web\JsonParser',
  4. ]
  5. ]

Info: The above configuration is optional. Without it, the API would only recognize application/x-www-form-urlencoded
and multipart/form-data input formats.

Summary

Not it’s time to check what we’ve created so far with that little effort. We already have RESTful API for getting and
managing book data:

  1. GET /books: list all books page by page;
  2. HEAD /books: show the overview information of book listing;
  3. POST /books: create a new book;
  4. GET /books/123: return the details of the book 123;
  5. HEAD /books/123: show the overview information of book 123;
  6. PATCH /books/123 and PUT /books/123: update the book 123;
  7. DELETE /books/123: delete the book 123;
  8. OPTIONS /books: show the supported verbs regarding endpoint /books;
  9. OPTIONS /books/123: show the supported verbs regarding endpoint /books/123.

Info: Yii will automatically pluralize controller names for use in endpoints. You can configure this using the
yii\rest\UrlRule::$pluralize.

You may also access your API via Web browser by entering http://localhost/web-service/web/books.
However, you may need some browser plugins to send specific request headers. For example,
Postman Chrome Extension:

Create Web Service - 图2


Back To Index

01. Introduction

02. Preparation

03. Create Web Service

04. Create Web Client

05. Customization

06. Conclusion