Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force JSON Response in CakePHP

Tags:

json

rest

cakephp

I've created 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 particular endpoint to respond in JSON. In the case above all requests made with the api prefix. For example:

http://localhost/api/products

Should return a JSON response instead of an HTML. Note that it should work that way even without the .json extension being defined.

like image 478
chrony Avatar asked Oct 18 '13 03:10

chrony


1 Answers

So I am guessing in your controller you check if the api prefix was set and if so you serialize the data you give back to the view? if so then just add:

$this->RequestHandler->renderAs($this, 'json');
like image 149
Alex Stallen Avatar answered Nov 18 '22 00:11

Alex Stallen