12

I am working with yii2 , and I want to create rest api. I read yii2 rest api quick start documentation, but in there you can use only default actions(index/view/create/delete/list...). It is working fine

But I want to create another action for example

public function actionPurchasedcard(){
     //some code
}

But I couldn't it. Help me please, how to create custome action in yii2 Rest api.

config.php

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        [
            'class'=>'yii\rest\UrlRule',
            'controller'=>[
                'v1/resource',
            ]
        ],
    ]
]

document root:

htdocs/myapi/api/web/

I am calling like this : http://myapi/v1/resource/purchasedcard

Thanks.(sorry my english not good)

Sardor Dushamov
  • 1,665
  • 3
  • 17
  • 44
  • 1
    This is the way but what happen?. "I couldn't" not help.. show your rest url and your controller – ScaisEdge Jul 30 '15 at 11:04
  • What URL do you use to call the action? Perhaps you should post your controller code here as well – Blizz Jul 30 '15 at 11:53

1 Answers1

24

You may set the extraPatterns key in a rule to add a new actions, like so:

'rules' => [
    [
        'class'=>'yii\rest\UrlRule',
        'controller'=>[
            'v1/resource',
        ],
        'extraPatterns' => [
            'GET purchasedcard' => 'purchasedcard',
        ]
    ],
]

You may want to add other properties to the rule such as prefix or only depending on what you want to achieve. Look at the full documentation to know more. Look at guide examples too: there is an example of an extraPattern with the search action near the end of this guide.

Mat
  • 2,134
  • 1
  • 18
  • 21