How to Create RestFul Api in CakePHP 3 with Mysql

Abhigyan Singh 30th Sep 2020

To have your app restfully is a good way to increase your app audience. REST API in CakePHP 3 with Mysql is an XML-based method to allow access to your app using HTTP headers. It is light, simple, and have well-organized formats that organize even a very complex application.

CakePHP and Rest

CakePHP 3 framework allows you to make your restful API in an easy way by two main steps:

Step1:  Configure resource routing

In ‘config/routes.php’, We will add these lines to allow REST access to TopicsController.

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

After setting up REST routes you can access your controller actions using URLs like this: https://yourdomain/Topics/index.json,https://yourdomain/Topics/view/2.json.The URL has a suffix of the REST format ‘JSON’ or ‘XML’.Or you will get an error message says that CakePHP misses the controller’s method.

Step 2: Serialize Output

If you have your Controller basic CRUD, you can modify it to serialize its output. So, Controller responses will be in JSON or XML format depending on the routes.

TopicsController.php will be like that

<?php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Cache\Cache;
classTopicsController extends AppController
{

public function initialize()
{

parent::initialize();
$this->loadComponent('RequestHandler');

}

public function index()
{
// find('all') get all records from Topics model
// We uses set() to pass data to view
$topics = $this->Topics->find('all');
$this->set([
'topics'=>$topics,
'_serialize'=>['topics']
]);

}

public function view($id)
{
// get() method get only one topic record using
// the $id paraameter is received from the requested url
// if request is /topics/view/5 the $id parameter value is 5
// if request is /topics/view/5.json the $id parameter value is 5
$topic = $this->Topics->get($id);

$this->set([
'topic'=>$topic,
'_serialize'=>['topic']
]);
}

public function add()
{
$topic = $this->Topics->newEntity();
//if the user topics data to your application, the POST request informations are registered in $this->request
if ($this->request->is('post')) { //
$topic = $this->Topics->patchEntity($topic, $this->request->data);
$topic->user_id = $this->Auth->user('id');
if ($this->Topics->save($topic)) {

$message = 'Topic saved';
}else{
$message = 'Error1';
}
}
$this->set([
'message' => $message,
'topic' => $topic,
'_serialize' => ['message', 'topic']
]);
}
public function edit($id = null)
{
$topic = $this->Topics->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Topics->patchEntity($topic, $this->request->data);
if ($this->Topics->save($topic)) {
$message = "Topic updated";
}else{
$message = "Error2";
}
}

$this->set([
'message'=>$message,
'topic'=>$topic,
'_serialize'=>['message','topic']
]);
}
public function delete($id)
{
//if user wants to delete a record by a GET request ,allowMethod() method give an Exception as the only available request for deleting is POST or delete for Rest http request
$this->request->allowMethod(['post', 'delete']);

$topic = $this->Topics->get($id);
if ($this->Topics->delete($topic)) {

$message = 'Topic deleted';
}else{
$message = 'Error3';
}
$this->set([
'message'=>$message,
'_serialize'=>['message']
]);
}
}
?>

You can see that weused_serialize variable to specify the variable that will be serialized into XML or JSON.

Accessing API

Try the index and view actions in your browser using the next URLs as they use the GET HTTP method.

https://yourdomain/topics/index.json

https://yourdomain/topics/index.xml

https://yourdomain/topics/view/2.json

https://yourdomain/topics/view/2.xml

add, edit, and delete actions uses POST HTTP method. So, If you don’t have an app capable of testing the Header’s Request.

You might use

REST Client plugin for Firefox

Postman Plugin for Chrome

Cocoa REST Client for Mac.

I am using the postman plugin with chrome.

In delete action, I queried https://localhost/topics/delete/26.json using the POST HTTP method and this was the response.


In add action, I queried https://localhost/topics/add.json using the POST HTTP method. And sent a user data with the request.
This was the JSON response.

In this tutorial, you learned the basics of using RESTful API in CakePHP.
If you have any questions feel free to write your comment.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk