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?

1

2 Answers 2

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

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

1 Comment

I know that. By I want json by default
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,
        ],
    ],

Comments

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.