Sammaye
Sammaye

Reputation: 43884

How to make RESTful routes in Cake3 without using extensions?

I want to make a RESTful API in my CakePHP application however, the only way it describes is using extensions (a.k.a file extensions) https://book.cakephp.org/3.0/en/development/routing.html#creating-restful-routes but this isn't feasible for me considering that I actually have JSON files that I do not wish to get confused with CakePHP, not only that but adding .json or whatever to the end of a path is likely to be missed and omitting it does not change that it will actually go there causing an error to show.

Is there a way to create RESTful routes without using extensions?

Upvotes: 1

Views: 282

Answers (1)

ndm
ndm

Reputation: 60463

Extensions are optional

Extensions are by no means required for RESTful routes to work. Extensions are part of how the request handler component configures the rendering and response process, the routes themselves will work just fine without specifying extensions.

It looks like the docs are kind of outdated, the sentence describing the code example doesn't make any sense:

The first line sets up a number of default routes for easy REST access where method specifies the desired result format (e.g. xml, json, rss). These routes are HTTP Request Method sensitive.

I guess this belongs to an older code example. You may want to report this over at GitHub.

Use the Accept header

That being said, the request handler component also evaluates the Accept header, so you could make sending application/json the requirement for your API.

Also if you don't want to accept non-JSON requests at all, then you should check Request::is() and throw an exception accordingly.

if (!$this->request->is('json')) {
    throw new \Cake\Network\Exception\BadRequestException():
}

Hardcode the components behavior

Furthermore it's possible to overwrite the extension that the request handler determines, and make the component think this is a JSON request:

$this->RequestHandler->ext = 'json';

It should be noted that this won't affect methods like RequestHandler::prefers()!

And finally you can also use the RequestHandler::renderAs() method to tell the request handler how to render and respond:

$this->RequestHandler->renderAs($this, 'json');

This however would need to be done in the Controller.beforeRender event in order to override the components behavior in case it identifies a request of a type that it is normally ment to handle.

See also

Upvotes: 2

Related Questions