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

Wednesday, January 5, 2022

[FIXED] removing compulsary .json extension for API Controller

 January 05, 2022     cakephp, cakephp-3.0, php     No comments   

Issue

is there a a way how to remove the compulsory .json extension from url? For example, I have a route /api/1.0/users.json and I would like to have just /api/1.0/users, which just shows warning that I don't have the index template set up.

Ideally, I would love to keep the option to have both XML and JSON output, bit have the json as a default that would not require the .json extension.

I use the crud plugin and my route looks like:

Router::prefix('api', function ($routes) {
    $routes->extensions(['json', 'xml']);
    $routes->resources('Users');
});

Using CakePhp 3. I am new to cake and so all help is very much appreciated.


Solution

It is not compulsory, it is just a tool for debugging and fast development. The right way of getting a json response, is telling Cake you want a json response using the HTTP headers.

Just send the Accept: application/json header in your request. When using jquery, do this:

$.ajax({url: '...', dataType: 'json', ...})

You can also force to ignore the headers in the controller:

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


Answered By - José Lorenzo Rodríguez
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

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