Buga1234
Buga1234

Reputation: 161

Yii2 Call api method from backend controllers

I have implemented API based on advanced template following Yii Rest API documentation. And I want to call API methods from backend controllers. Is it possible to do?

Thanks

Upvotes: 4

Views: 4026

Answers (3)

Buga1234
Buga1234

Reputation: 161

So, I finally found a solution.

My Yii2 application has advanced template. I've created api module.

So app has 3 endpoints

  • api
  • backend
  • frontend

And I wanted to call api methods from backend or frontend, It's not important.

So the main goal here that api is the module. You can read about this here

In backend/config/main.php

'modules' => [
    'api' => [
        'basePath' => '@api/modules/v1',
        'class' => 'api\modules\v1\Module'
    ]
],

And then for example

in backend/UserController/indexAction

$res = Yii::$app->runAction('api/user/index');

That how it works. Hope it will help to someone.

Upvotes: 4

ScaisEdge
ScaisEdge

Reputation: 133360

A way could be this .

Assuming that you rest controller is in frontend

In your backend application config you could create an additional 'UrlManager' component name eg: urlManagerForRest

return [
  'components' => [
      'urlManager' => [
          // here is your backend URL rules
      ],
      'urlManagerForRest' => [
          'class' => 'yii\web\urlManager',
          'baseUrl' => 'http://your_path/frontend/web/index.php',
          'enablePrettyUrl' => true,
          'showScriptName' => false,
      ],

  ],
];

Then you should invoke following to compose URL:

Yii::$app->urlManagerFrontEnd->createUrl();

Upvotes: 1

AliLotfi
AliLotfi

Reputation: 430

you can use postman for testing your api. first download your version of postman then choose your method. then determine your inputs and your url. and finally press send button. your url might be like

http://yourdomain.com/backend/web/index.php?r=yourController/yourAction

that yourdomain.com is your domain and yourController are controller and yourAction are your action.

Upvotes: -1

Related Questions