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

Wednesday, March 9, 2022

[FIXED] In cakephp3 how do I create a REST API where output types can be defined as either JSON or XML?

 March 09, 2022     api, cakephp-3.0, php, rest, routes     No comments   

Issue

New to cake and struggling with the basics. I want to create an API which essentially gives database access to users.

So, I want something like the following for my routes:

-/myAPI/view/viewname.xml -/myAPI/view/viewname.json

Essentially, these urls will return all data in the view defined in either xml or JSON.

Here is an example of a route I have created for a View:

use Cake\Core\Plugin;
use Cake\Routing\Router;

Router::defaultRouteClass('Route');

Router::scope('/', function ($routes) {
    $routes->connect('/', ['controller' => 'Homepage', 'action' => 'index']);
});

Router::scope('/myAPI', function ($routes) {
    $routes->extensions(['json', 'XML']);
    $routes->resources( 'View',
            ['only' => ['view'],
            'id'=>'[0-9a-zA-Z]+']);
});

Plugin::routes();

When I navigate to /myAPI/view/name.xml I get:

<response>
<message>Invalid input.</message>
<url>/myAPI/View/name.xml</url>
<code>500</code>
</response>

Here is my view method in the controller:

public function view($viewname)
{
$response = array('foo' => 'bar');

$this->set('response', $response);
$this->set('_serialize', 'response');
}  

It works with .json however but not with .xml. Why is this?

Thanks


Solution

If the json response is working try the following

Router::scope('/myAPI', function ($routes) {
$routes->extensions(['json', 'xml']);
});

Instead of 'XML'

I also recommend you this tutorial.

EDIT:

I just implemented in the controller

public function view($viewname)
{
    $response = array('foo' => 'bar');
    $this->set('response', $response);
    $this->set('_serialize', 'response');
}

In routes.php

Router::scope('/myAPI', function ($routes) {
$routes->extensions(['json', 'xml']);
});

Using this URL:

myAPI/controllername/view/name.xml

I get a succesful response.

Check your URL I believe you are missing the controller name.



Answered By - Danny Sandi
  • 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