Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - creating an API for my cakephp app

I have created a fully functional CakePHP web application. Now, i wanna get it to the next level and make my app more "opened". Thus i want to create an RESTful API. In the CakePHP docs,i found this link (http://book.cakephp.org/2.0/en/development/rest.html) which describes the way to make your app RESTful. I added in the routes.php the the two lines needed,as noted at the top of the link,and now i want to test it. I have an UsersController.php controller,where there is a function add(),which adds new users to databases. But when i try to browse under mydomain.com/users.json (even with HTTP POST),this returns me the webpage,and not a json formatted page,as i was expecting .

Now i think that i have done something wrong or i have not understood something correctly. What's actually happening,can you help me a bit around here?

Thank you in advace!

like image 385
Kostas Livieratos Avatar asked Jan 12 '23 14:01

Kostas Livieratos


1 Answers

You need to parse JSON extensions. So in your routes.php file add:

Router::parseExtensions('json');

So a URL like http://example.com/news/index you can now access like http://example.com/news/index.json.

To actually return JSON though, you need to amend your controller methods. You need to set a _serialize key in your action, so your news controller could look like this:

<?php
class NewsController extends AppController {

    public function index() {
        $news = $this->paginate('News');
        $this->set('news', $news);
        $this->set('_serialize', array('news'));
    }
}

That’s the basics. For POST requests, you’ll want to use the RequestHandler component. Add it to your controller:

<?php
class NewsController extends AppController {

    public $components = array(
        'RequestHandler',
        ...
    );

And then you can check if an incoming request used the .json file extension:

public function add() {
    if ($this->RequestHandler->extension == 'json') {
        // JSON request
    } else {
        // do things as normal
    }
}
like image 70
Martin Bean Avatar answered Jan 21 '23 15:01

Martin Bean