Question

I have this in my routes file:

CakePlugin::routes();
Router::mapResources('api');
Router::parseExtensions('json');

Currently if I call a controller I have Api with .json as an extension as long as it's a HTTP GET (not post) it outputs json which is fine, no matter the method/function name as long as it exists in my Api controller.

If I make a post, whilst I can decode the posted JSON whatever function/method I've called, it errors saying I'm missing xxx.ctp in app/Api/Views/json/ xxx.ctp = the name of any function I've called to post.

2 Questions/problems.

Ideally I want to parse any request to the Api controller as json, but without having to specify the .json extension in the url.

Secondly, how/why can't the HTTP POST output json like the HTTP GET, do I need to map something else somewhere?

Many thanks

Was it helpful?

Solution

If you want to render everything from a specific controller (in your case, ApiController.php) as JSON without requiring the user to append the .json extension on their request, you can use renderAs and setContent in your beforeFilter.

    public function beforeFilter() {
       parent::beforeFilter();
       $this->RequestHandler->setContent('json');
       $this->RequestHandler->renderAs($this, 'json');
    }

renderAs and setContent are part of RequestHandler.

This does mean that this controller will never return anything other than json. If your happy with that, you can even remove extension catcher in your routes.php file...

Router::parseExtensions('json');

Remembering that if you remove the above line from your routes.php file, a request to your ApiController of any kind will result in a 404 being thrown (not as JSON).

Developing further using the beforeFilter you can actually render as different content-types depending on the type of request. For example..

    public function beforeFilter() {
       parent::beforeFilter();
           if ($this->RequestHandler->isGet()) {
               $this->RequestHandler->setContent('json');
               $this->RequestHandler->renderAs($this, 'json');
           }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top