Reputation: 332
I just used Yii2 to build an Application to be backend for Flutter App
so .. I created a modules/api folder and I've create controllers inside it , like this
<?php
namespace app\modules\api\controllers;
use yii\web\Controller;
use yii\rest\ActiveController;
class AdController extends ActiveController
{
public $modelClass = 'app\models\Ad';
}
and its works fine but its return XML
i tried in web.php
'components' => [
'response' => [
'format' => \yii\web\Response::FORMAT_JSON,
],
],
and
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
but it still return XML
Update
when i use
'urlManager' => [
....
'enableStrictParsing' => true,
...
]
it give me Not Found (#404)
Upvotes: 0
Views: 1121
Reputation: 784
First of all create a base controller
and override behaviour method with this configuration
namespace micro\controllers;
class ActiveController extends yii\rest\ActiveController {
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['contentNegotiator'] = [
'class' => 'yii\filters\ContentNegotiator',
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
]
];
return $behaviors;
}
}
than extend it in all your project controller
contentNegotiator key is responsible for response format
Upvotes: 2
Reputation: 4412
You can try in the controller action put:
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON
For example:
public function actionAd()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
// return response
}
However you should add the class for serialize
class AdController extends ActiveController
{
public $modelClass = 'app\models\Ad';
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
}
Upvotes: 0