CakePHP 3 Tutorial 22: Serving JSON Data

Submitted by naidim on Sun, 05/21/2017 - 09:09

Serving JSON (JavaScript Object Notation) from CakePHP 3 is somewhat straight-forward, but there can be a few "gotchas" so I've written this tutorial to help others and as a reminder to myself. With the goal of presenting your CakePHP data as JSON data, here are the steps you need to follow. According to the CakePHP book ( https://book.cakephp.org/3.0/en/views/json-and-xml-views.html ) data views requires the RequestHandler component. This is typically enabled by default in your application, but if not simply add the following to your src/Controller/AppController.php file.

public function initialize()
{
    ...
    $this->loadComponent('RequestHandler');
    ...
}

In your config/routes.php file, add the following to allow serving of .json files.

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

Now, if you've already set up any models and controllers, you should already see something new when you simply browse to the appropriate path. e.g. http://www.example.com/users/index.json

{
    "users": [
        {
            "id": 1,
            "username": "admin",
            "email": "webmaster@naidim.org",
            "role": "Admin",
            "created": "2016-12-15T13:30:15",
            "modified": "2016-12-31T14:39:26"
        }
    ]
}

Now this may or may not be all you need, however, some people have more specific needs, so instead of letting Cake do the work for you, you can do it manually in your Controller function.

public function data()
{
    ...
    $this->RequestHandler->respondAs('json');
    $this->response->type('application/json');
    $this->autoRender = false;
    echo json_encode($resources);
}

Your output will be a little different:

[{"id": 1,"username": "admin","email": "webmaster@naidim.org","role": "Admin","created": "2016-12-15T13:30:15","modified": "2016-12-31T14:39:26"}]

Also remember, $this->autoRender = false; disables the default display, so the data action path will not work for anything other than JSON data.

Tags

Add new comment