PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 17, 2022

[FIXED] Force JSON format using CakePHP 3 and Crud plugin

 January 17, 2022     cakephp, cakephp-3.0, crud     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing