Saturday, October 24, 2015

Yii2: RESTful api: tutorial

1. Install Yii2

Download, install and verify the installation of Yii2 (I'm using the advanced application template) .
Instructions: https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/start-installation.md

2. Folder structure

  • \
    • api
      • config
      • modules
        • v1
          • controllers
          • models
      • runtime
        • cache
        • debug
        • logs
      • web
    • backend
    • common
    • ...

3. Files

3.1 Add files

I copied the files from the backend directory and edited them afterwards. (Some files have been created manually)
  • \
    • api
      • config
        • main.php
        • main-local.php
        • params.php
        • params-local.php
      • modules
        • v1
          • controllers
            • ArtistController.php
          • models
            • Artist.php
        • Module.php
      • runtime
        • cache
        • debug
        • logs
      • web
        • .htaaccess
        • index.php
    • backend
    • common
    • ...

3.2 Edit files

\common\config\main-local.php

Configure the database correctly

\api\config\main.php
  • Change the id from 'app-backend' to 'app-api'
  • Remove the controllerNamespace
  • Change the modules to:
    'modules' => [
            'v1' => [
                'basePath' => '@app/modules/v1',
                'class' => 'api\modules\v1\Module'
            ]
        ],
  • Add the the components:
    'request' => [
     'parsers' => [
      'application/json' => 'yii\web\JsonParser',
     ]
    ],
    'urlManager' => [
     'enablePrettyUrl' => true,
     'enableStrictParsing' => true,
     'showScriptName' => false,
     'rules' => [
      [
       'class' => 'yii\rest\UrlRule', 
       'controller' => 'v1/artist',
       'tokens' => [
        '{id}' => '<id:\\w+>'
       ],
       'extraPatterns' => [
        // 'GET alive' => 'alive',
       ],
      ]
     ],        
    ]
\api\config\main-local.php
  • Change $config to $config = [];
\api\modules\v1\controllers\ArtistController.php

Change the file to:
<?php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;

/**
 * Artist Controller API
 *
 * @author Unknown
 */

class ArtistController extends ActiveController
{
    public $modelClass = 'api\modules\v1\models\Artist';

 // Default actions
 // GET /artists: list all artists
 // HEAD /artists: show the overview information of artist listing
 // POST /artists: create a new artist
 // GET /artists/AU: return the details of the artist AU
 // HEAD /artists/AU: show the overview information of artist AU
 // PATCH /artists/AU: update the artist AU
 // PUT /artists/AU: update the artist AU
 // DELETE /artists/AU: delete the artist AU
 // OPTIONS /artists: show the supported verbs regarding endpoint /artists
 // OPTIONS /artists/AU: show the supported verbs regarding endpoint /artists/AU.

 public function actions()
 {
        $actions = parent::actions();
 // Possibility to unset default actions
        // unset($actions['index']);
        return $actions;
 }

 // Define custom actions
 // public function actionAlive()
 // {
 //     return new ActiveDataProvider([
 //         'query' => Proxy::find()->where(['Alive' => 1]),
 //         'pagination' => false,
 //     ]);
 // }
}
\api\modules\v1\models\Artist.php

Use GII to generate your model.

Make sure that the use and the namespace is correct:

namespace api\modules\v1\models;

use \yii\db\ActiveRecord;

\api\modules\v1\Module.php

Change the file to:

<?php

namespace api\modules\v1;

class Module extends \yii\base\Module
{
    public $controllerNamespace = 'api\modules\v1\controllers';

    public function init()
    {
        parent::init();
    }
}

\api\web\.htaccess

Change the file to:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php

\api\web\index.php

Change the file to:
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../../common/config/main.php'),
    require(__DIR__ . '/../../common/config/main-local.php'),
    require(__DIR__ . '/../config/main.php'),
    require(__DIR__ . '/../config/main-local.php')
);

$application = new yii\web\Application($config);
$application->run();
\common\bootstrap.php

Add to the file:

Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');

4. Test

Navigate to: http://localhost:8080/Music%20api/advanced/api/web/v1/artists

Expected result:
<response>
   <item>
      <Id>31</Id>
      <Name>Mampi Swift</Name>
   </item>
   <item>
      <Id>32</Id>
      <Name>Psion</Name>
   </item>
   <item>
      <Id>33</Id>
      <Name>Perfect Combination</Name>
   </item>
</response>

5. References

No comments:

Post a Comment