How to return JSON instead of XML by default in Web Service ?

I have set up my restfull UserController like in the guide : http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html

When I want to display one user, I visit this url: localhost/api/users/1 , and I get xml response. How can I get JSON by default for all my controllers ?

In config/main.php insert this component, inside ‘component’ node:




'components' => [

    ...

    ...

    

        'response' => [

        

            'format' => yii\web\Response::FORMAT_JSON,

            'charset' => 'UTF-8',

        ], 

    ...

    ...

]



Thanks, but I still get xml. BTW I am using basic template.

What kind of input are you sending? xml or json?

I am not sending any input, I am just visiting page localhost/api/users/1 in my browser. Everything else is set up exactly like in guide, same code.

In guide when you do this you get JSON: http://www.yiiframework.com/doc-2.0/guide-rest-resources.html

Try to add in your controller:




	public function behaviors()

	{

        $behaviors = parent::behaviors();

        

        $behaviors['contentNegotiator'] = [

	            'class' => 'yii\filters\ContentNegotiator',

	            'formats' => [

	                'application/json' => Response::FORMAT_JSON,

	            ]

        ];

        

        return $behaviors;

	}	



I also had to add use yii\web\Response;

Yes now it returns JSON. But can this be configured somehow globally for all controllers ?

Sure!

Create a BaseController and extend every controller in the module from that BaseController.

Hmm, its strange that you can not configure this in application configuration. Thank you for your help !

The response goes as json if the client send the corresponding http header




Accept:application/json



http://www.yiiframew…formatting.html

If this header is not present the response is in xml

Rest client send this header automatically, browser no.

Thats why you get and xml accessing with a browser, try with a rest client or add the above header to your browser using an extension.

You can force json response globally in bootstrap section of your application configuration configuring the ContentNegotiator

http://www.yiiframework.com/doc-2.0/yii-filters-contentnegotiator.html#$formats-detail




	'bootstrap' => [

    	[

        	'class' => 'yii\filters\ContentNegotiator',

        	'formats' => [

            	'application/json' => Response::FORMAT_JSON,

        	],

    	],

	],



[color="#006400"]/* Moved from "General Discussions" to "REST APIs" */[/color]