[Yii2] Create a RESTful API

An API is 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 the yii2 advanced template.

TOP TUTORIALS:  Prevent Windows 10 Specific Updates

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”.
yii2 api 01
  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
yii2 api 02
  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:  Windows 11 bypass TPM and CPU
yii2 api 03

B. Yii Configuration

  1. Create a Controller

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

<?php
namespace apicontrollers;
use yiirestActiveController;
 
class UserController extends ActiveController
{
    public $modelClass = 'commonmodelsUser';
}
  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' => 'yiiwebJsonParser',
            ]
        ],
        .........
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yiirestUrlRule', '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
yii2 api 04
  1. Or with the CURL command
yii2 api 05
  1. You can also access it through a browser with the URL “”http://localhost/yii2-advanced/api/web/users”
yii2 api 06
Ads Blocker Image Powered by Code Help Pro
Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

I Have Disabled The AdBlock, Reload Now
Powered By
CHP Adblock Detector Plugin | Codehelppro