0

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)

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

there is something i need to know when i Used 'enableStrictParsing' => true, i can't access s to my controller actions it gives me not found 404 what is my mistake ?
0

You can try in the controller action put:

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON

For example:

public function actionAd()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    // return response
}

However you should add the class for serialize

 class AdController extends ActiveController
 {
     public $modelClass = 'app\models\Ad';
     public $serializer = [
         'class' => 'yii\rest\Serializer',
         'collectionEnvelope' => 'items',
     ];
 }

2 Comments

I need the all application return json , Not separately
No it doesn’t return json too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.