How to create a REST API for Yii2-basic-template

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

I created a table called users , a controller called UserController

 <?php namespace app\controllers; use yii\rest\ActiveController; class UserController extends ActiveController { public $modelClass = 'app\models\User'; } ?> 

and online

  '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 an error on page 404. Any help would be appreciated

+6
source share
2 answers

With these configurations:

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

Your resources should be available at these URLs:

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

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

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

You also need to configure your server before enabling Pretty Urls by adding a .htaccess file with this content to your web folder if you are using apache server (pls link to the link below if you are 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 was not described in the documentation at the link you provided, because it expected you to complete the setup and server configuration section:

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

+4
source

Rest Api is very easy to implement in the base Yii2 application. Just follow these steps. This code works 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'; } 

link

+7
source

All Articles