1

I've configured rest api like this: http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html

How to make Yii2 rest api output json by default instead of XML?

varan
  • 795
  • 2
  • 10
  • 29
  • 1
    Possible duplicate of [RESTful response how to return JSON instead of XML in Yii2?](http://stackoverflow.com/questions/33639985/restful-response-how-to-return-json-instead-of-xml-in-yii2) – ldg Jul 21 '16 at 17:43

2 Answers2

0

From the client you use:

curl -i -H "Accept:application/json" "http://localhost/myendpoint"

It does seem like JSON should be the default, however Yii2 it's XML. See:

RESTful response how to return JSON instead of XML in Yii2?

and/or dig deeper into the docs: http://yiiframework.com/doc-2.0/yii-filters-contentnegotiator.html

Community
  • 1
  • 1
ldg
  • 9,112
  • 2
  • 29
  • 44
0

This depends on what do you mean by default. Possible options:

  1. you just want to show json if you open your endpoint in browser
  2. client wasn't sent Accept: header
  3. client was sent Accept: header but no one of requested formats is not supported by your endpoint

In first case, you just should define json by default for text/html.

In second case also add application/octet-stream because it is defined as default in the HTTP protocol (proof, proof). You can also make proper configuration in your nginx or apache if this not works.

In the third case ContentNegotiator will throw exception 415 Unsupported Media Type. You can also handle it via web server configuration, but this will be wrong. I.e. if the client requested an image and only image you should not send json because this can be unacceptable for client. With HTTP header 415 client will be properly notified that the format is not supported.

I use the following config for my projects with API:

$config = [
    'as contentNegotiator' => [
        'class' => \yii\filters\ContentNegotiator::className(),
        'formatParam' => '_format',
        'formats' => [
            'application/octet-stream' => \yii\web\Response::FORMAT_JSON,
            'text/html' => \yii\web\Response::FORMAT_JSON,
            'application/json' => \yii\web\Response::FORMAT_JSON,
            'application/xml' => \yii\web\Response::FORMAT_XML,
        ],
    ],
Community
  • 1
  • 1
oakymax
  • 1,454
  • 1
  • 14
  • 21