Search code examples
phpjsonlithium

Lithium return json response with request header accept:application/json


I have a lithium app and I try to return json response when the header request has Accept:application/json (I would like to avoid using the type parameter in my route)

I add this instruction in my app/bootstrap/media.php but I still have a html response

Media::type('json', array('application/json'), array(
    'conditions' => array('type' => true)
));

What did I miss ?

I saw a similar question but it seams that the framework evolved : PHP lithium(li3) how to set up automatic response with JSON


Solution

  • Because content negotiation involves some overhead, it is not enabled by default. To enable it, simply add the following to your controller:

    protected function _init() {
        $this->_render['negotiate'] = true;
        parent::_init();
    }
    

    Also, you don't need the Media configuration, as JSON is configured by default.