Speaktech.in

Yii2 Building a RESTful API

In the Yii2 there is a front-end and back-end tree, and this is extensible. To separate out the API features, we'll create a third tree to as API endpoint.


$ cp -R frontend api

$ cp -R environments/dev/frontend/ environments/dev/api

$ cp -R environments/prod/frontend/environments/prod/api


And I added the api alias to /common/config/bootstrap.php:

<?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');


In /api/config/main.php, we need to add the request[] to parse setup JSON parsing and the UrlRule to associate methods for the models and their endpoints:

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

return [

    'id' => 'app-api',

    'basePath' => dirname(__DIR__),

    'controllerNamespace' => 'api\controllers',

    'bootstrap' => ['log'],

    'modules' => [],

    'components' => [

      'request' => [

        'parsers' => [

          'application/json' => 'yii\web\JsonParser',

        ],

      ],

      'urlManager' => [

        'enablePrettyUrl' => true,

        'enableStrictParsing' => true,

        'showScriptName' => false,

        'rules' => [

          ['class' => 'yii\rest\UrlRule', 'controller' => 'item'],

          ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],

        ],

      ],

That's basically all it takes to enable some rich API functionality for these models.