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
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.