Yii2 Rest api call multiple methods

Hi All,

I am using this piece of code, and try using REST API in yii2.

I tried to use two function as you seen in the code snippet.

  1. getAllData

  2. getSpecificData




<?php


namespace app\api\modules\widgetmodule\controllers;


use yii\rest\Controller;


class WidgetController extends Controller

{

    public $modelClass = 'app\models\DynamicWidget';

    

    public function actions()

    {

        return [

            'index' => [

                'class' => 'yii\rest\IndexAction',

                'modelClass' => $this->modelClass,

                'prepareDataProvider' => [$this, 'getAllData']

            ],

            'view' => [

                'class' => 'yii\rest\ViewAction',

                'modelClass' => $this->modelClass,

                'prepareDataProvider' => [$this, 'getSpecificData']

            ],

        ];

    }


    public function getAllData()

    {

        die('get all data');

    }

    

    public function getSpecificData()

    {

        die('get specific data');

    }

}



I tried two URLs for the two different methods,


http://localhost/api/web/widgetmodule/widget/getAllData


http://localhost/api/web/widgetmodule/widget/getSpecificData

But the output will always be like.

Here is my URL manager code in api.php




'urlManager' => [

            'enablePrettyUrl' => true,

            'enableStrictParsing' => true,

            'showScriptName' => false,

            'rules' => [

                '<controller:\w+>/<action:\w+>/<id:\w+>' => '<controller>/<action>',

                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',

                [

                    'class' => 'yii\rest\UrlRule',

                    'controller' => ['widgetmodule/widget']

                ]

            ],

        ], 

        'db' => $db,

    ],

    'modules' => [

        'widgetmodule' => [

           'class' => 'app\api\modules\widgetmodule\Module',

        ],

So could anyone help me, how to get different outputs with two different methods.

It is anyways calling the first method.

Any help will be appreciated.

Thanks in advance.

try this:




'rules' => [

    [

        'class' => 'yii\rest\UrlRule', 

        'controller' => ['widgetmodule/widget'], 

        'patterns' => [

            'GET index'  => 'index',

            'GET view' => 'view',

        ]

    ],

],



Thanks Salem! For your response.

But no luck. :(

Now the URL not found error occured.

Scrrenshot is attached here.

Thanks.

Try:





[

                    'class' => 'yii\rest\UrlRule',

                    'controller' => 'widgetmodule/widget',

                    'extraPatterns' => [

                        'GET GetAllData' => 'GetAllData',

                    ]

                ],




And add action to the function name such as actionGetAllData.