[Yii2] Create a RESTful API

Table of Contents

An API is a software that integrates the applications we create with other applications. The purpose of the creation is to share data between applications that have been integrated.

The RESTful API/REST API is the application of the API(Application Programming Interface). REST(Representational State Transfer)is an architecture of communication methods that uses the HTTP protocol for data exchange where this method is often applied in application development. With the aim to make the system have good performance, fast and easy to develop (scale) especially in the exchange and communication of data.

Building a REST API in Yii is actually quite easy. You can take advantage of the existing MVC framework, but you create different access points that you want to access by different types of services (not website visitors).

Here, we use an example to illustrate how you can build a set of RESTful APIs with little coding effort. The Yii we will use is yii2 advanced template.

TOP TUTORIALS:  DHCP Server Configuration with Multiple VLAN Cisco Packet Tracer

Assume you want to expose user data via RESTful APIs. The user table in this example you created when you first installed Yii. For how to install Yii you can see on How to Install Yii2 Advanced via Composer.

Steps to Create a RESTful API on Yii2 Advanced

A. Create endpoint APIs

In the Yii2 Advanced template, we have a backend and frontend directory. To separate the API features, we’ll create a new directory named “api” as the endpoint.

  1. Copy the backend directory and rename it to “fire”.
  1. Edit the“common/config/bootstrap.php”file and add an alias for “fire”.
<?php
Yii::setAlias('@common', dirname(__DIR__));
Yii::setAlias('@frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('@backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');
  1. In the “environments/dev” directory, copy the backend directory and rename it to “fire”. Likewise for the “environments / prod” directory, so it will look like the following image
  1. Adjust the “environments/index.php” file as follows
return [
    'Development' = > [
        'path' = > 'dev',
        'setWritable' = > [
            ..........,
            'api/runtime',
            'fire/web/assets',
        ],
		..............
        'setCookieValidationKey' = > [
            ..........,
            'api/config/main-local.php',
        ],
    ],
    'Production' = > [
        'path' = > 'prod',
        'setWritable' = > [
			..........,
            'api/runtime',
            'fire/web/assets',
        ],
		.............
		'setCookieValidationKey' = > [
			..........,
            'api/config/main-local.php',
        ],
    ],
];
  1. In the fire directory we created earlier, change all the words “backend” to “fire”
TOP TUTORIALS:  How to Uninstall Windows 10 Updates

B. Yii Configuration

  1. Create a Controller

Create a“UserController” file in the “api/controllers” directory and copy the following scripts

<?php
namespace api\controllers;
use yii\rest\ActiveController;
 
class UserController extends ActiveController
{
    public $modelClass = 'common\models\User';
}
  1. Configuration of RULES AND JSON Input URL

Change the “api/config/main.php” file by adding the JSON request and URL Rule as follows:

return [
    .........
    'components' => [
        'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
        .........
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
            ],
        ]
        ............
    ],
    ............
];
  1. Create a “.htaccess” file in the “api/web/” directory and copy the following code
	RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php
    RewriteRule ^index.php/ - [L,R=404]

C. API testing

  1. Download Postman,then open Postman. Make a request to the “http://localhost/yii2-advanced/api/web/users” URL
  1. Or with the CURL command
  1. You can also access it through a browser with the URL “”http://localhost/yii2-advanced/api/web/users”

Leave a Comment

Your email address will not be published. Required fields are marked *