Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom action in Yii2 Rest API

Tags:

rest

api

yii2

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)

like image 473
Sardor Dushamov Avatar asked Jul 30 '15 09:07

Sardor Dushamov


1 Answers

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.

like image 167
Mat Avatar answered Nov 15 '22 22:11

Mat