D
D
des1roer2017-07-15 05:38:44
Yii
des1roer, 2017-07-15 05:38:44

Yii2 how to make api for front?

There is such a structure for basic
GL9sUGVWQlmg-nolz3KT6A.png
modules/api/v1/controllers/PersController.php

<?php

namespace api\modules\v1\controllers;

use app\models\Pers;
use yii\rest\ActiveController;

class PersController extends ActiveController
{
    public $modelClass = Pers::class;

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['corsFilter' ] = [
            'class' => \yii\filters\Cors::className(),
        ];

        return $behaviors;
    }
}

config/web.php
'urlManager' => [
            'class' => 'yii\web\UrlManager',
            // Disable index.php
            'showScriptName' => false,
            'enableStrictParsing' => true,
            // Disable r= routes
            'enablePrettyUrl' => true,
            'rules' => array(
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            //    'signup' => '/myshop/default/signup',
            //    'submitsignup' => '/myshop/submitsignup',
                ['class' => 'yii\rest\UrlRule', 'controller' => 'api/v1/pers'],
            ),
        ],
        'request' => [
            'enableCookieValidation' => true,
            'enableCsrfValidation' => true,
            'cookieValidationKey' => '-Ghw8jpJL-0okgil5QLXZdNW2tHJIiBT',
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
    ],
    'modules' => [
        'admin' => [
            'class' => 'app\modules\admin\Module',
        ],
        'user' => [
            'class' => 'amnah\yii2\user\Module',
        ],
        'api' => [
            'class' => 'app\modules\api\v1\Module',
        ],
    ],

but
aWM6tNiMSUCr3Rjg8Ms6BA.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Morev, 2017-07-19
@amorev

yii\rest\UrlRule adds its own logic to the formation of requests and for it to work you need to add s at the end of the endpoint. For example, if the controller is UserController, then to activate the REST rules for processing urls, you need to make a request like this:
GET (PUT, POST): /api/v1/users
Also, as padlyuck noted , you have problems with the namespace. For example, you have PersController in a completely different namespace (api\modules\v1\controllers), when the module itself is, judging by the configuration, app\modules\api\v1\Module. This layout is obviously not working - your module controller is located in a completely different place, unlike the module.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question