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)

2
  • 1
    This is the way but what happen?. "I couldn't" not help.. show your rest url and your controller Commented Jul 30, 2015 at 11:04
  • What URL do you use to call the action? Perhaps you should post your controller code here as well Commented Jul 30, 2015 at 11:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also to pass params you can do the following: 'GET purchasedcard/<some_id>' => 'purchasedcard',

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.