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 controllersbeforeFilter()
callback: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: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.
First of all, setup your Router in
routes.php
file.Router::parseExtensions("json");
Then add RequestHandler component to the controller (it's required for automatic MIME-type recognition by HTTP headers and choosing correct View Class).
public $components = array('RequestHandler');
Now, you are able to receive JSON querying any controller method with .json extension, or by specifying HTTP
Accept
header with the same effect, without extension needs to be specified.curl -H "Accept: application/json" http://example.com/recipies