Last updated on March 13th, 2020 at 11:44 am

Cakephp is one of my favorite framework, and with the time Cakephp improve and add lots of new feature in it and made easy to develop large scale application. In my last post i explain how to setup your Cakephp application. Now in this post i am going to explain how we can create web service in Cakephp in few minutes.Web services in cakephp 3

Before we start building our first web service in Cakephp i hope you already setup you Cakephp  and  your web app is working with some raw data for testing.

if not then it’s okay you can bake your cake with few command as shown in video. Please follow video to understand and demonstrate what we actually going to make. For this post i have a user table in which i can perform CURD operation using CakePHP REST API.

CREATE TABLE `users` (
  `id` int(10) UNSIGNED NOT NULL,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `role` varchar(20) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Copy above SQL and paste in your database and download sample code from above download link.

CakePHP REST API

Step 1. Now first we can add JSON extension in our routes file so we can load json data from URL,

Add

$routes->setExtensions(['json']);

before

$routes->fallbacks('DashedRoute');

Step 2. Now in this step we can update in some of method so we can get json response. For this we can remove redirects and flash messages as shown code below

<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Users Controller
 *
 * @property \App\Model\Table\UsersTable $Users
 */
class UsersController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $users = $this->paginate($this->Users);

        $this->set(compact('users'));
        $this->set('_serialize', ['users']);
    }

    /**
     * View method
     *
     * @param string|null $id User id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
		$res = array();
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data);
            if ($this->Users->save($user)) {
				// Remove flash and redirections
				$res['status'] = 1;
                $res['msg'] = 'The user has been saved.';
            } else {
				$res['status'] = 0;
                $res['msg'] = 'The user could not be saved. Please, try again.';
            }
        }
        $this->set(compact('res'));
        $this->set('_serialize', ['res']);
    }

    /**
     * Edit method
     *
     * @param string|null $id User id.
     * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);
		$res = array();
        if ($this->request->is(['patch', 'post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->data);
            if ($this->Users->save($user)) {
				$res['status'] = 1;
				$res['msg'] = 'User updated successfully';
            } else {
				$res['status'] = 0;
                $res['msg'] = 'The user could not be saved. Please, try again.';
            }
        }
        $this->set(compact('res'));
        $this->set('_serialize', ['res']);
    }

    /**
     * Delete method
     *
     * @param string|null $id User id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
		$res = array();
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);
        if ($this->Users->delete($user)) {
			$res['status'] = 1;
            $res['msg'] = 'The user has been deleted.';
        } else {
			$res['status'] = 0;
            $res['msg'] = 'The user could not be deleted. Please, try again.';
        }
        
		$this->set(compact('res'));
        $this->set('_serialize', ['res']);
    }
}

Step 3. After updating your controller you can use any REST Client for this tutorial iam using POSTMAN.

API URL: Paste below url in your rest client and run

GET USER LIST:  http://localhost/cakeservice/users/index.json

GetUserList in cakephp service - trinitytuts

View User: http://localhost/cakeservice/users/view/{user_id}.json

ViewUser cakephp json service - trinitytuts

Edit User: http://localhost/cakeservice/users/edit/{user_id}.json

Edit user info cakephp webservice - trinitytuts

Delete User: http://localhost/cakeservice/users/delete/{user_id}.json

Delete user from rest apr cakephp 3 - trinitytuts

To view its working you can download code from above link or you can view video. This post is very basic and easy for beginners.