RestFul Api in CakePHP 3 with Mysql

To have your app restfully is a good way to increase your app audience. REST 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 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: http://yourdomain/Topics/index.json ,http://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 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 next URLs as they use GET HTTP method.

http://yourdomain/topics/index.json

http://yourdomain/topics/index.xml

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

http://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 Header’s Request.

You might use

REST Client plugin for Firefox

Postman Plugin for Chrome

Cocoa REST Client for Mac.

I am using postman plugin with chrome.

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

In add action, I queried http://localhost/topics/add.json using 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 REST in CakePHP.
If you have any questions feel free to write your comment.

Share this Article on Social Media

All of my Scripts are ready to customized as per your requirement. Feel free to contact for script customization.

Contact me at discussdesk@gmail.com

"Note : It will be charged as per your customization requirement :)"

Get Updates, Scripts & Other Tutorials to Directly to your Email

Over 20000+ Happy Readers already subscribed. (We don't send spam email). Every email subscriber can get our latest updates and download our 100+ scripts.

Comments