Skip to content
CODE THE PIXEL
CakePHP

CakePHP 4 Application Programming Interface (API)

Asyraf Wahi Anuar Updated 3 min read

This tutorial described how to create an API for adding, editing, listing and deleting records in CakePHP 4.

This tutorial may be outdated

It was last reviewed 3 years ago. Some steps may differ in newer versions.

Tech stack

  • CakePHP 4.x

Application Programming Interface is referred to as API. Any software with a specific function is referred to as an application when discussing APIs. The interface can be compared to a service agreement between two programmes. This agreement specifies the requests and responses the two parties will use to communicate. Many application developers are aware of the necessity of making their core functionality accessible to a wider audience. Unrestricted access to the main API can aid in accepting the application platform and permit mashups and system integration.

This tutorial demonstrates the 'articles’ table as a reference model for API in CakePHP 4. Using the CakePHP shell, run the following command to bake the model and controller:

Terminal
bin/cake bake model Articles --no-validation --no-rulesbin/cake bake controller  Article --no-actions --prefix Api

Configure the routes as follows:

PHP
$routes->prefix('Api', function (RouteBuilder $builder) {
	$builder->setExtensions(['json', 'xml']);
		$builder->connect('/add', ['controller' => 'Articles', 'action' => 'add']);
		$builder->connect('/index', ['controller' => 'Articles', 'action' => 'index']);
		$builder->connect('/edit/{id}', ['controller' => 'Articles', 'action' => 'edit'])->setPass(['id']);
		$builder->connect('/delete/{id}', ['controller' => 'Articles', 'action' => 'delete'])->setPass(['id']);
});

Remove these lines of code from middleware() method in …\src\Application.php

src/Application.phpPHP
->add(new CsrfProtectionMiddleware([
    'httponly' => true,
]))

The Article Controller in …src\Controller\Api\ArticlesController.php should be configured as follows:

Controller/Api/ArticlesController.phpPHP
<?php
declare(strict_types=1);

namespace App\Controller\Api;

use App\Controller\AppController;

class ArticlesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel('Articles');
    }
	
	public function add()
    {
        $this->request->allowMethod(['post']);

        // form data
        $formData = $this->request->getData();

        // title check rules
        $articleData = $this->Articles->find()->where([
            'title' => $formData['title']
        ])->first();

        if (!empty($articleData)) {
            // already exists
            $status = false;
            $message = 'Title already exists';
        } else {
            // insert new article
            $articleObject = $this->Articles->newEmptyEntity();

            $articleObject = $this->Articles->patchEntity($articleObject, $formData);

            if ($this->Articles->save($articleObject)) {
                // success response
                $status = true;
                $message = 'Article has been created';
            } else {
                // error response
                $status = false;
                $message = 'Failed to create article';
            }
        }
        $this->set([
            'status' => $status,
            'message' => $message
        ]);

        $this->viewBuilder()->setOption('serialize', ['status', 'message']);
    }
	
    public function index()
    {
        $this->request->allowMethod(['get']);

        $articles = $this->Articles->find()->toList();

        $this->set([
            'status' => true,
            'message' => 'Article list',
            'data' => $articles
        ]);

        $this->viewBuilder()->setOption('serialize', ['status', 'message', 'data']);
    }	
	
    public function edit()
    {
        $this->request->allowMethod(['put', 'post']);

        $article_id = $this->request->getParam('id');

        $articleInfo = $this->request->getData();

        // article check
        $article = $this->Articles->get($article_id);

        if (!empty($article)) {
            // article exists
            $article = $this->Articles->patchEntity($article, $articleInfo);

            if ($this->Articles->save($article)) {
                // success response
                $status = true;
                $message = 'Article has been updated';
            } else {
                // error response
                $status = false;
                $message = 'Failed to update article';
            }
        } else {
            // article not found
            $status = false;
            $message = 'Article Not Found';
        }

        $this->set([
            'status' => $status,
            'message' => $message
        ]);

        $this->viewBuilder()->setOption('serialize', ['status', 'message']);
    }
	
    public function delete()
    {
        $this->request->allowMethod(['delete']);
        
        $article_id = $this->request->getParam('id');

        $article = $this->Articles->get($article_id);

        if (!empty($article)) {
            // article found
            if ($this->Articles->delete($article)) {
                // article deleted
                $status = true;
                $message = 'Article has been deleted';
            } else {
                // failed to delete
                $status = false;
                $message = 'Failed to delete article';
            }
        } else {
            // not found
            $status = false;
            $message = 'Article does not exists';
        }

        $this->set([
            'status' => $status,
            'message' => $message
        ]);

        $this->viewBuilder()->setOption('serialize', ['status', 'message']);
    }
	
}

To submit article data from API, download POSTMAN application.

PHP
POST: http://localhost/folderName/api/add.json

Header:
Accept: application/json
Content-Type: application/json

Body:
{
	"title": "CakePHP",
	"content": "This is a CakePHP Development",
	"author": "Asyraf"
}

To request the list of articles:

PHP
GET: http://localhost/folderName/api/index.json

The controller has included edit and delete functions. The developer may test it using POSTMAN.

That’s all. Happy coding.

Did this tutorial help?

62 readers found this helpful

Comments

No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

Using Bahasa Melayu Table Names in CakePHP

Learn how to use Bahasa Melayu table names like "pengguna" in CakePHP while following the framework’s naming conventions. Includes tips for using the Bake tool and avoiding pluralization issues.

5 min read

Tools & Software

Formatting PHP in VSCode Using Prettier and PHP Intelephense

Learn how to set up Visual Studio Code (VSCode) for automatic PHP file formatting using the Prettier and PHP Intelephense extensions. This step-by-step tutorial will help you maintain a clean and organised codebase, enhancing your PHP development experience.

2 min read