6

I wanted to create a REST API for a yii2 basic template. I followed the following link.

I created a table named users, a controller named UserController

<?php
namespace app\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
}
?>

and in the web

   'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
    ],
],

        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '4534',
            'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ],
        ],  

my file name is restapi so i tried this url http://localhost/~user/restapi/web/ all i get is a 404 page not found error. Any help would be appreciated

ankitr
  • 5,512
  • 7
  • 40
  • 66
Bloodhound
  • 2,720
  • 8
  • 31
  • 66

2 Answers2

8

Rest Api is very simple to to implement in Yii2 basic app. Just follow the steps below. This code is working for me.

application structure

yourapp
+ web
+ config
+ controllers
...
+ api
  + config
  + modules
    + v1
      + controllers
  .htaccess
  index.php

api/index.php

<?php

// comment out the following two lines when deployed to production
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');

// Use a distinct configuration for the API
$config = require(__DIR__ . '/config/api.php');

(new yii\web\Application($config))->run();

api/.htaccess

Options +FollowSymLinks
IndexIgnore */*

RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php

api/config/api.php

<?php

$db     = require(__DIR__ . '/../../config/db.php');
$params = require(__DIR__ . '/params.php');

$config = [
    'id' => 'basic',
    'name' => 'TimeTracker',
    // Need to get one level up:
    'basePath' => dirname(__DIR__).'/..',
    'bootstrap' => ['log'],
    'components' => [
        'request' => [
            // Enable JSON Input:
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                     // Create API log in the standard log dir
                     // But in file 'api.log':
                    'logFile' => '@app/runtime/logs/api.log',
                ],
            ],
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/project','v1/time']],
            ],
        ], 
        'db' => $db,
    ],
    'modules' => [
        'v1' => [
            'class' => 'app\api\modules\v1\Module',
        ],
    ],
    'params' => $params,
];

return $config;

api/modules/v1/Module.php

<?php
// Check this namespace:
namespace app\api\modules\v1;

class Module extends \yii\base\Module
{
    public function init()
    {
        parent::init();

        // ...  other initialization code ...
    }
}

api/modules/v1/controllers/ProjectController.php

<?php
namespace app\api\modules\v1\controllers;

use yii\rest\ActiveController;

class ProjectController extends ActiveController
{
    // We are using the regular web app modules:
    public $modelClass = 'app\models\Project';
}

reference

GAMITG
  • 3,670
  • 7
  • 30
  • 50
ankitr
  • 5,512
  • 7
  • 40
  • 66
5

With those configurations :

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

your resources should be available within those urls :

http://localhost/~user/restapi/web/users

http://localhost/~user/restapi/web/users/1

  • Note: Yii will automatically pluralize controller names for use in endpoints unless you configure the yii\rest\UrlRule::$pluralize property to not do so.

Also you need to configure your server before enabling Pretty Urls by adding a .htaccess file with this content to your web folder if using apache server ( pls refer to link below if using nginx ) :

# Set document root to be "basic/web"
DocumentRoot "path/to/basic/web"

<Directory "path/to/basic/web">
    # use mod_rewrite for pretty URL support
    RewriteEngine on
    # If a directory or a file exists, use the request directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # Otherwise forward the request to index.php
    RewriteRule . index.php

    # ...other settings...
</Directory>

This part wasn't described in the documentation of the link you provided as it was expecting that you did follow the installation & server configuration section :

http://www.yiiframework.com/doc-2.0/guide-start-installation.html#configuring-web-servers

Salem Ouerdani
  • 6,956
  • 2
  • 37
  • 47