Still new to YII2, and im working on a already build YII2 project(learning on the spot) but I can’t find the correct url/path to my newly added API page(s).
Not sure if there is something missing in the code, wrong paths or whatever.
If have tried:
(not working on localhost)
www.example.com/v1/product/
www.example.com/web/product
www.example.com/v1/product/web/product
…
application structure
+ api
+ config
- main.php
+ modules
+ v1
+ controllers
- ProductController.php
+ models
- Product.php
- RestModule.php
+ web
- .htaccess
- index.php
+ backend
+ common
+ frontend
api/config/main.php
<?php
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__).'/..',
'bootstrap' => ['log'],
'modules' => [
'v1' => [
'class' => 'api\modules\v1\RestModule',
]
],
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/product',
]
],
]
]
];
api/modules/v1/controllers/ProductController.php
<?php
namespace api\modules\v1\controllers;
class ProductController extends yii\rest\ActiveController
{
public $modelClass = 'api\modules\v1\models\Product';
public function actionIndex(){
echo 'product controller';
}
}
api/modules/v1/models/Product.php
<?php
namespace api\modules\v1\models;
class Product extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'product';
}
public function rules()
{
return [
[['description', 'name'], 'string']
];
}
}
api/modules/RestModule.php
<?php
namespace api\modules\v1;
class RestModule extends \yii\base\Module
{
public $controllerNamespace = 'api\modules\v1\controllers';
public function init()
{
parent::init();
echo 'restmodule';
}
}
api/web/index.php
<?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/aliases.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
}
$application = new yii\web\Application($config);
$application->run();
api/web/.htaccess
RewriteEngine on
# Order Deny,Allow
# Deny from all
# Allow from 10.30.2.0/24
# Allow from 37.153.242.179
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule \.(gif|png|jpg|jpeg)$ /img/blank.gif [L,R=302]
# 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