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
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
So, I finally found a solution.
My Yii2 application has advanced template. I've created api module.
So app has 3 endpoints
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.
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();
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.