Cakephp create a simple API

This tutorial for cakephp version 4, here we will learn how we can create a simple API using cakephp.

Our goal is we will create an API to save category if doesn’t exist !

Very beginning we will create a resources route in cakephp. Here, you may ask what is the resource route ? Answer is resource route will accept all http VERBS. Example GET,POST,PUT,DELETE,PUT

Now let’s go in cakephp source in location config/routes.php Go to the end of the line and create a new route scope for your API. Example 

$routes->scope('/api', function (RouteBuilder $routes) {
   $routes->setExtensions(['json']);
   $routes->resources('Categories',[

       'path' => 'category',
       'prefix' => 'Api',
       'map' => [

           'addCategory' => [
               'action' => 'addCategory',
               'method' => 'POST',
               'path' => '/add-category'
           ],
       ]
   ]);
});

Here , You can see I have created a route for my categories controller where I have an action called addCategory

So, Let’s create a class in location src/Controller/Api
Note : Create a folder with name Api, because in route we have used prefix Api

Now your CategoriesController.php will looks like below.

 

<?php

namespace App\Controller\Api;
use App\Controller\AppController;
use Cake\Event\EventInterface;
use Cake\ORM\TableRegistry;

Class CategoriesController extends AppController 
{
   public function addCategory()
   {

       $this->request->allowMethod(['post']);
       $category = $this->Categories->patchEntity($this->Categories->newEmptyEntity(), $this->request->getData());
       $this->set('category',$this->Categories->findOrCreate(
                   ['name'=>$this->request->getData('name')],
                   function()use($category){
                       return $category;
                   }
               )
           )
       ;
       $this->viewBuilder()->setOption('serialize', ['category']);
    }
}

Don’t forget to create a model for categories ! You can use a simple bake command to create a model for categories table.

bin/cake bake model categories

So, We have done it ! Now let’s test in postman , you can test it postman using below URL

http://localhost/api/category/add-category.json

Set body name = your-category-name

Also send a post request !