Create a Restful API with Apigility
On 7th October 2013, Zend introduced Apigility which allows us to create a web service very easily. We can create a simple REST API that allows us to view a list of music albums, showing how to start using Apigility and how to publish an API using this tool.
Apigility is an open source and allows us as a composer to create an Apigility project. Move to project location and then run the below command.
$ composer.phar create-project -sdev zfcampus/zf-apigility-skeleton music
This in turn installs the Apigility skeleton project.
Apigility provide an administration system which allows us to create and manage the APIs that our application will provide. In live site the administration pages should not be accessible and so Apigility controls this concept of development mode.We can enable or disable development mode with the following command:
$ php public/index.php development enable (or) disable.
On enable, a new config file “ config/development.config.php” is created in Apigility.
Navigate to Apigility Development Screen
To navigate to Apigility development screenà type http://localhost:8080/apigility/ui
To view all existing àAPIs select APIs menu.
To create new API, choose the APIs menu à click Create New API option:
Enter an API name of “TestAPI” and click Create API button. The Apigility admin will then create our own API for us. Now Apigility will create a new ZF2 module, called TestAPI and registers the module.
API versioning with Apigility
The current version of this API is 1. Apigility also supports for versioning using Create New Version option.
The API is managed with the below admin interface:
Create a Rest endpoint
Step to create a new API:
- Select REST Servicesmenu option on the left of the Music admin page.
- Select Create New REST Service
- Two different types of REST services is provided: Code-Connected or DB-Connected.
A DB-Connected REST service uses ZF2’s Table Gateway component to expose a CRUD interface to a single database table.
When requirements are complex, then the Code-Connected REST service allows you full control which is more preferred. Type”Album” as the REST Service Name and press the “Create Code-Connected REST Service” button. Which creates REST endpoint called Album.
Apigility creates defaults for a REST endpoint, so we don’t need to change anything. The most common setting that needs to be checked is Route matches which defines the URL to reach this service. For our new service, it is /album[/:album_id] which is a standard Zend\Route definition. This will call methods from this service whenever the URL starts with /album with an optional second segment containing an id.
Test the API with curl
We can test our new API with curl commands.