问题
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!
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/19202294/cakephp-rest-api-remove-the-necessity-of-format