RESTful response how to return JSON instead of XML in Yii2?

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,
      ],
    ],
  ];
}

Just set the Response's format in your application configuration:

'components' => [
    ... // config
    'response' => [
        'format' => \yii\web\Response::FORMAT_JSON
    ],
    ... // config
]

Tags:

Yii2