No need to manually set header like that.
In the specific action / method you can set it like so:
use Yii;
use yii\web\Response;
...
public function actionIndex()
{
Yii::$app->response->format = Response::FORMAT_JSON;
}
Then after that just return a simple array like that:
return ['param' => $value];
You can find this property in official docs here.
For more than one action using special ContentNegotiator filter is more flexible approach:
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => ContentNegotiator::className(),
'only' => ['index', 'view']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
];
}
There are more settings, you can check it in official docs.
As for the REST, base yii\rest\Controller already has it set for json and xml:
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],