I am new in Yii2 and I am trying to create a simple RESTful API using the advanced app (frontend - backend)
In a very few steps I managed to get some response, but I can’t get it in JSON.
I have:
a frontend\models\Engineer model
a frontend\controllers\EngineerController
<?php
namespace frontend\controllers;
use yii\rest\ActiveController;
class EngineerController extends ActiveController
{
public $modelClass = 'frontend\models\Engineer';
}
and this is what I added to my configuration on frontend/config/main.php
What i mean - can you try to use POSTMAN to make a call, and set Accept header to type ‘application/json’. If this will return xml, then it looks like your config doesn’t work. Your code seems to be ok and in proper places and it’s probably some mistake - for example in index.php you’re referring to wrong config file or something like that.
Not sure if it helps, but my config is different than yours. In web config I have:
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'QMX0HrP82Cr0QJP55TqD1hjlFuh3xv_5',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
That’s definitely outputting json for me when I use curl or postman.
try adding ?_format=json to your url. it should work. by forcing json output.
you’re getting xml output because Accept header type is not set to ‘application/json’ as mentioned by @marcinu. and that is what postman as most frontend app usually do by default.
you helped me thank you but it just working in single controller is there any other solution to run get json format from all controller instead of putting this code in all controller