Are you creating an API in CakePHP? This task looks very popular these days, and most of our clients need an API to expose certain services to their own rich client applications, or third party services. Even if it's easy to configure CakePHP to expose a REST API, and there are other plugins that could help you building an API, we found ourselves working on specific tweaks per project to adjust the way the API was designed, so we decided to wrap all these ideas and create a specific CakePHP API Plugin including
- Services definition
- Integrated CRUD
- Nested resources
- Pagination
- Sorting
- Associations
- Versioning
- Custom Extensions (data format / transformers)
- Self documentation
We've gathered all the best practices around API building and CakePHP and wrapped them into an easy to install and setup Plugin to be used as the foundation of your API intensive CakePHP projects.
Let's walkthru some of the Plugin features using an example application: the bookmarker tutorial http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html
We'll assume you've already created a new CakePHP application and configured it to use the bookmarker database (schema dump here http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html#creating-the-database).
Setting up the CakePHP API Plugin
Download the plugin first
composer require cakedc/cakephp-api:dev-master
Then ensure plugin is loaded in you bootstrap.php file
Plugin::load('CakeDC/Api', ['bootstrap' => true, 'routes' => true]);
Now you have an API!
Test your newly configured "default" API using curl
curl -X GET http://bookmarker.dev/api/bookmarks
You'll get something similar to:
{ "status": "success", "data": [], "pagination": { "page": 1, "limit": 20, "pages": 0, "count": 0 }, "links": [ { "name": "self", "href": "http:\/\/bookmarker.dev\/api\/bookmarks", "rel": "\/api\/bookmarks", "method": "GET" }, { "name": "bookmarks:add", "href": "http:\/\/bookmarker.dev\/api\/bookmarks", "rel": "\/api\/bookmarks", "method": "POST" } ] }
If you look at the provided output you'll identify we've used a JSend default renderer (status, data) and we append some extra data under 'links' (HATEOAS dynamically generated for your CRUDs) and pagination.
The specific "extensions" used can be configured and custom extensions created for your specific needs, see https://github.com/CakeDC/cakephp-api/blob/master/docs/Documentation/extensions.md
We'll publish a couple tutorials soon covering some of the features implemented, and explaining how did we use the CakePHP API Plugin to address specific use cases.
Meanwhile, please check the documentation here https://github.com/CakeDC/cakephp-api/blob/master/docs/Documentation/overview.md
Giving back to the community
This Plugin's development has been sponsored by the Cake Development Corporation. Contact us if you are interested in:
- Professional, commercial CakePHP development and CakePHP consulting
- Professional CakePHP training
- CakePHP code review