The problem is that responses from RESTful server in Yii2 come back as XML, and I need them to be in JSON format.
I was following the guide from Yii2, the controller looks the same, the model is kind of different, it is connected to a database (the model was previously copied from a default model in an advanced template), and web config is also the same like the guide.
Just to clarify any doubts, here is the code:
UserController.php
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
web.php ($config)
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'WgkzlqvStTfGXY-ToFlQIJRDMX4LUQtY',
'parsers'=>[
'application/json'=>'yii\web\JsonParser'
]
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'params' => $params,
];
I tried settings in the config component:
response=>[
'format'=>yii\web\Response::FORMAT_JSON
]
...but it still responds with XML. What do I do to make it respond with JSON?
You can set it initially on call like below:
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
For example:
public function actionView($id) {\
Yii::$app - > response - > format = \yii\ web\ Response::FORMAT_JSON;
$user = \app\ models\ User::find($id);
return $user;
}
You can also use ContentNegotiator
filter in your class behaviors like below:
/**
* @inheritdoc
*/
public function behaviors() {
return [
[
'class' => \yii\ filters\ ContentNegotiator::className(),
'only' => ['index', 'view'],
'formats' => [
'application/json' => \yii\ web\ Response::FORMAT_JSON,
],
],
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With