yii2yii2-basic-appyii2-api

Yii2 : Rest API return xml instead of json


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)


Solution

  • 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