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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With