Force JSON response in CakePHP

I created the routes shown below:

Router::connect('/:api/:controller/:action/*', array(), array('api'=>'api')); Router::connect('/:api/:controller', array('action' => 'index'), array('api'=>'api')); Router::connect('/:api/', array('controller' => 'index', 'action' => 'index'), array('api'=>'api')); 

Basically, I want all requests made through a specific endpoint to respond in JSON. In the case above all requests made with the api prefix. For instance:

 http://localhost/api/products 

Should return a JSON response instead of HTML. Note that it should work this way even if the .json extension is not defined.

+6
source share
1 answer

So, I assume that in your controller you are checking if the api prefix has been set, and if you serialize the data that you return to view? if so just add:

 $this->RequestHandler->renderAs($this, 'json'); 
+8
source

Source: https://habr.com/ru/post/956213/


All Articles