V
V
Vladimir2018-04-02 11:11:56
Yii
Vladimir, 2018-04-02 11:11:56

Yii2 rest api 404 error, what did you do wrong?

Good day! I did everything as per the instructions, but I feel that I didn’t write something 100% correctly, since the instruction was made simpler, but for me it’s a bit not simple.
I use an advanced template, there is such a path: backend/modules/media_library/сontrollers/rest/
In this folder, lie MediaLibraryController.php

<?php
namespace backend\modules\media_library\controllers\rest;

use yii\rest\ActiveController;

class MediaLibraryController extends ActiveController
{
    public $modelClass = 'backend\modules\media_library\models\MediaLibrary';
}

I added [b]parsers[/b] and the controller to the backend config file:
'components' => [
    'request' => [
        'csrfParam' => '_csrf-backend',
        'baseUrl' => '/admin',
        'parsers' => [
            'application/json' => 'yii\web\JsonParser',
        ],
        'cookieValidationKey' => 'key',
    ],
    ...
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            '' => 'site/index',
            '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
            ['class' => 'yii\rest\UrlRule', 'controller' => 'media_library'],
        ],
    ]
],

Well, it's understandable when requesting https://site.com/media_librarys and https://site.com/admin/media_librarys throws out a 404 error...
Please tell me how to be and what I'm doing wrong?
Thanks in advance for the replies!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir, 2018-04-03
@MasterGerold

The error was in the line where I specified the controller, it would, of course, be specified incorrectly.
Corrected for

['class' => 'yii\rest\UrlRule', 'controller' => 'media-library/rest/media-library']
and everything works.

D
Dmitry Kim, 2018-04-03
@kimono

Did you add the module to the config?

'components' => [
  //...
],
'modules' => [
  'media_librarys' => [
    'class' => backend\modules\media_library\Module::class
  ]
]

G
German Fedorov, 2020-01-28
@German_Fedorov

Для таких же ищущих ответ на этот вопрос поясню:
1. UrlRule ждет пропертю controller, которая в доке описана как ID контроллера, но это не совсем так. Если используете Advanced template, то надо указать и имя модуля moduleName/controller (user/auth).
2. Если вы также, как и я используете единственное число в именовании, то не забудьте выключить нафиг pluralize.
Тогда конечный вариант для меня выглядел так

['class' => 'yii\rest\UrlRule', 'controller' => 'user/auth', 'pluralize' => false],

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question