2
votes

I've been following a few tutorials online but I can't seem to figure out how to create a REST API for Yii2. I keep getting a 404 page not found. This is what I have so far:

Folder structure:

api
- config
-- api.php
-- bootstrap.php
- modules
-- v1
--- controllers
---- UserController.php
--- Api.php
--- Module.php
.htaccess
index.php

api/api.php

<?php

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

$config = [
    'id' => 'api',
    'basePath'  => dirname(__DIR__).'/..',
    'bootstrap'  => ['log'],

    'components'  => [
        // URL Configuration for our API
        'urlManager'  => [
            'enablePrettyUrl'  => true,
            'showScriptName'  => false,

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

        ],

        'request' => [
            // Set Parser to JsonParser to accept Json in request
            'parsers' => [
                'application/json'  => 'yii\web\JsonParser',
            ]
        ],

        'cache'  => [
            'class'  => 'yii\caching\FileCache',
        ],

        // Set this enable authentication in our API
        'user' => [
            'identityClass'  => 'app\models\User',
            'enableAutoLogin'  => false, // Don't forget to set Auto login to false
        ],

        // Enable logging for API in a api Directory different than web directory
        'log' => [
            'traceLevel'  => YII_DEBUG ? 3 : 0,
            'targets'  => [
                [
                    'class'  => 'yii\log\FileTarget',
                    'levels'  => ['error', 'warning'],
                    // maintain api logs in api directory
                    'logFile'  => '@api/runtime/logs/error.log'
                ],
            ],
        ],

        'db'  => require(__DIR__ . '/../../config/db.php'),
    ],

    'modules' => [
        'v1' => [
            'basePath' => '@api/modules/v1',
        'class' => 'api\modules\v1\Api',
        ]
    ],

    'params'  => $params,
];

return $config;

api/bootstrap.php

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

api/modules/v1/controllers/UserController.php

<?php

namespace app\api\modules\v1\controllers;

class UserController extends ActiveController
{

    public $modelClass = 'app\models\User';
}

api/modules/v1/Api.php

<?php

namespace api\modules\v1;

use \yii\base\Module;

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

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

        // custom initialization code goes here
    }
}

api/modules/v1/Module.php

<?php

namespace api\modules\v1;

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

    public function init()
    {
        parent::init();
        \Yii::$app->user->enableSession = false;
        // custom initialization code goes here
    }
}

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/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__ . '/config/bootstrap.php');

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

$application = new yii\web\Application($config);

$application->run();

mod_rewrite is enabled

Not sure what else needs to be done from here. I also have this added to common/config/main.php

'modules' => [

    'user' => [
        'class' => 'dektrium\user\Module',            
    ],

    'v1' => [
        'basePath' => '@api/modules/v1',
        'class' => 'api\modules\v1\Api',
    ]

],

I use Postman to send GET requests: http://example.com/api/v1/users

and

http://example.com/v1/users which returns Class app\api\modules\v1\Api does not exist

I made a few changes to the configuration and files, but no luck. This is the cleanest version I have.

1
'class' => 'app\api\modules\v1\Api', does not match your namespace in Api.php and Module.php. - h2ooooooo
Changed, But still get 404 not found when using http://example.com/api/v1/users. Also changed in question. - Ciprian

1 Answers

0
votes

Please try this

Your controller name is UserController and you are accessing users in api

try to access user in api url