Building REST APIs using CakePHP 3.x

Narendra Vaghela
SprintCube Blog

--

We use CakePHP for most of our PHP based applications. And most of them have mobile apps or services which are connected using the REST APIs. Each application has its structure and flows to manage the APIs. But the general workflow would be:

1) Get request
2) Perform operation
3) Return the response

And to achieve these, we use a standard code package, and recently we have converted it into a Plugin and open sourced it so that others can get the benefit of it. We have named it — CakePHP REST.

It simplifies the REST API development for your CakePHP 3 application. It converts the output of your controller into a JSON response.

Installation

Similar to every PHP package, install it using composer.

composer require sprintcube/cakephp-rest

And load it into your CakePHP application by adding it to your bootstrap.php.

Plugin::load('Rest', ['bootstrap' => true]);

Or using the bake command.

$ bin/cake plugin load -b Rest

Basic Usage

This plugin requires almost 0 configurations. Simply create a controller and extend it to Rest\Controller\RestController.

<?php

namespace App\Controller;

use Rest\Controller\RestController;

/**
* Foo Controller
*
*/
class FooController extends RestController
{

/**
* bar method
*
* @return Response|void
*/
public function bar()
{
$bar = [
'falanu' => [
'dhikanu',
'tamburo'
]
];

$this->set(compact('bar'));
}
}

And set a parameter isRest to true in your route configuration,

$routes->connect('/foo/bar', ['controller' => 'Foo', 'action' => 'bar', 'isRest' => true]);

The output of the above action would be,

{
"status": "OK",
"result": {
"bar": {
"falanu": [
"dhikanu",
"tamburo"
]
}
}
}

It’s that simple.

Read the detailed documentation and examples here — https://bit.ly/cakephprest

Post any of your questions or queries here.

--

--

Narendra Vaghela
SprintCube Blog

Co-founder at SprintCube & Solution Architect | CakePHP Developer