Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp REST API remove the necessity of .format

I am working on creating a REST api that will only get and return JSON data.

I'm following the cake guide and my default routes are like this:

GET     /recipes.format
GET     /recipes/123.format
POST    /recipes.format
PUT     /recipes/123.format
DELETE  /recipes/123.format
POST    /recipes/123.format

However, I really dislike the necessity of using the ".format" (".json" in my case) since I will only ever be accepting json.

I feel like there has to be a way to remove this necessity. I could use .htaccess to rewrite URLS, but I feel like there must be a way to do this in a cake setting / config file somewhere.

In short, I want to be abe to GET /recipes and have it output the same thing as GET /recipes.json would.

THANKS!

like image 417
Thomas Avatar asked Oct 05 '13 20:10

Thomas


1 Answers

I assume you are using the RequestHandler component. One way would then be to hardcode the extension in your controllers beforeFilter() callback:

public function beforeFilter()
{
    parent::beforeFilter();
    $this->RequestHandler->ext = 'json';
}

That way it would always use the JSON View and appropriate response headers, even if extension parsing is enabled and a non-.json extension was supplied in the URL.

Another option would be to use RequestHandlerComponent::renderAs() in your individual controller actions:

public function index()
{
    $this->RequestHandler->renderAs($this, 'json');
    ...
}

That would have the same effect, but you would need to do this in all of your actions, so in case the controllers solely purpose is to handle REST requests, you are probably better off overriding the extension.

like image 61
ndm Avatar answered Oct 05 '22 06:10

ndm