6
votes

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.

1

1 Answers

9
votes

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');