Issue
I have followed How to build a CakePHP 3 REST API tutorial to create REST API. Tutorial describes case when requests are made with extensions (json/xml) to set response format. Plugin CRUD for CakePHP is used.
I want to force JSON response format without using .json extension. I am getting MissingRouteException on my requests.
What have I tried
Router::prefix('api', function ($routes) {
//$routes->extensions(['json', 'xml']);
$routes->resources('Cocktails');
});
plus
#1
$this->RequestHandler->ext = 'json'
into AppController::beforeFilter()
#2
$this->RequestHandler->renderAs($this, 'json');
into AppController::beforeFilter()
but this is trying to use template from Template/Api/Coctails/json
I want it to behave exactly like in the case with extension.
Thanks
Solution
Request your data with a proper HTTP accept header Accept: application/json
, the RequestHandler should pick it up then.
The Accept header is used by HTTP clients to tell the server what content types they'll accept. The server will then send back a response, which will include a Content-Type header telling the client what the content type of the returned content actually is.
However, as you may have noticed, HTTP requests can also contain Content-Type headers. Why? Well, think about POST or PUT requests. With those request types, the client is actually sending a bunch of data to the server as part of the request, and the Content-Type header tells the server what the data actually is (and thus determines how the server will parse it).
In particular, for a typical POST request resulting from an HTML form submission, the Content-Type of the request will normally be either application/x-www-form-urlencoded or multipart/form-data.
Answered By - floriank
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.