Before created API with prefixes. So I had API in the controller folder with everything else but when you have many controllers it can be hard to navigate between them. So I decided to move all API controllers to a new plugin that I called Api (the similarity of the names is purely random). And the second good thing on this is that you can have easily versions of your API. So here I using prefixes for API versioning (V1, V2 …).
How to do it
First time create new plugin
1
php bin/cake.php bake plugin Api
And load it in Application.php bootstrap function.
1
2
3
4
// src/Controller/AppController.php
// add this to bootstrap function at the end
$this->addPlugin('Api');
Next, you need to allow to use URL extensions, for me it is .json. You can also allow .xml if you need this. If you want more extensions check the official documentation for CakePHP. Open and edit your plugin’s AppController
// /plugins/Api/src/Plugin.php
publicfunctionroutes(RouteBuilder$routes):void{$routes->plugin('Api',['path'=>'/api'],function(RouteBuilder$builder){// Add custom routes here
// API ver 1.0 routes
// add new block for more prefixes
$builder->prefix('V1',['path'=>'/v1'],function(RouteBuilder$routeBuilder){;$routeBuilder->setExtensions(['json']);// allow extensins. this have to be here for each prefix
$routeBuilder->fallbacks();});$builder->fallbacks();});parent::routes($routes);}
Update or create your actions in the API controller as following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// plugins/Api/src/Controller/V1/HelloController.php
publicfunctionindex(){$this->Authorization->skipAuthorization();$text=['message'=>'Hello'];$this->set('text',$text);// Add this to serialize repose
$this->viewBuilder()->setOption('serialize','text');}
You can test it with curl. And if everything goes OK you will see the result
Bonus If you want to post data to API you will be going to receive an error message as a response because the CSRF token doesn’t match. By default CakePHP 4 using Middleware so you have
set it to skip verification CSRF for plugin routes. Here is how to do it.
Copy or write following function at the end to your Application.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/Application.php
publicfunctiongetCsrfProtectionMiddleware():CsrfProtectionMiddleware{$csrf=newCsrfProtectionMiddleware(['httponly'=>true,]);$csrf->skipCheckCallback(function($request){if($request->getParam('plugin')=='Api'){// Skip Checking if plugin is API
returntrue;}});return$csrf;}
curl -i --data message="Hello from data" http://localhost:8765/api/v1/hello/index.json
To see your message from a post, update the index function do following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// plugins/Api/src/Controller/V1/HelloController.php
publicfunctionindex(){$this->Authorization->skipAuthorization();$text=['message'=>$this->request->getData('message'),];$this->set('text',$text);// Add this to serialize repose
$this->viewBuilder()->setOption('serialize','text');}