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:
bin/cake bake model Articles --no-validation --no-rules
bin/cake bake controller Article --no-actions --prefix Api
Configure the routes as follows:
$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
->add(new CsrfProtectionMiddleware([
'httponly' => true,
]))
The Article Controller in …src\Controller\Api\ArticlesController.php should be configured as follows:
<?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.
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:
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.