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?
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?
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
This depends on what do you mean by default. Possible options:
Accept:
header Accept:
header but no one of requested formats is not supported by your endpointIn 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,
],
],