Вы находитесь на странице: 1из 6

2016

php[tek]

The Premier Professional


PHP Conference
with a Community Flair
2016
July 17th-23rd, 2016
cruise.phparch.com Saint Louis
May 23rd - 27th
tek.phparch.com

2
FEATURE

Build APIs on Existing Web


Applications with Apigility
Michelangelo van Dam

DisplayInfo()

Requirements: Apigility is an API Builder,


Minimum requirement designed to simplify
• PHP 5.3.23 or higher
Recommended requirement
creating and maintaining
• PHP 5.4.8 or higher (to use built-in PHP web server) useful, easy to consume,


Other Software:
Apigility—http://www.apigility.org
and well-structured
• MySQL 5.0+ APIs. Regardless of your
• SQLite 3.6+
experience in API-building,
Related URLs:
with Apigility you can
• PHP—http://php.net
• MySQL—http://www.mysql.com build APIs that enable


PECL/PDO—http://php.net/pdo
Silex—http://silex.sensionlabs.org
mobile apps, developer
• Slim—http://www.slimframework.com communities, and any


Frapi—https://frapi.github.io
ZendCon—http://zendcon.com
other consumer-controlled
access to your applications.
18 | January 2016 www.phparch.com
Build APIs on Existing Web Applications with Apigility

Theialive Homepage FIGURE 1


We Already Have a Web
Application!
Let’s go back to the beginning of 2012. One of our
customers had a Zend Framework 1 application for
simple task management called TheiaLive; Figure 1
shows the homepage. REST APIs were a novelty at
the time and nobody really took notice of it.

Fast-forward to early 2013. The Internet was


moving toward a mobile consumer market and our
customer was eager to also move in that direction.
They asked me if our company could provide
an API so an external company could develop a
native mobile app.

Our first idea was to build it on our own using


a microframework like Slim, Silex, or plain PHP.
We had spent months building a REST-ish API
service on the side of our application, but ended up Apigility Announcement FIGURE 2
throwing it all away when Apigility was announced.
We hadn’t really thought about how to handle
versioning, providing hypermedia links, or having
documentation updated after each change.

We also looked at a variety of API managers


like Frapi to handle our REST API needs. Frapi
http://getfrapi.com is a native API framework
designed to build, maintain, and secure RESTful
endpoints. At first, Frapi seemed to be a perfect fit,
but we ended up missing some essential abilities to
reuse what we had already prepared in the original
application.
• event authentication using HTTP Basic/Digest or
OAuth2
The Big Announcement
It even provides API documentation (HTML,
Apigility was first announced at ZendCon Swagger)!
2013 by Matthew Weier O’Phinney
(http://twitter.com/mwop) during one of the
keynotes. It was immediately obvious that Apigility Setting Up Apigility
was a game-changer for everyone building and
When we started using Apigility we were a bit at a
managing APIs. Figure 2 shows my reaction on Twitter
loss: How could we integrate our old Zend Framework
http://phpa.me/tw-dragonbe-apigility.
1 application into this fancy Zend Framework 2 API
manager without having to duplicate our business
Apigility is, in essence, an API front end, but comes
logic all over? We first tried to tie Apigility into our
with a full-featured management interface. Apigility
existing application, but this didn’t work out well
provides RESTful or RPC services with JSON. Some of
as we got into conflict between the class name
its features include:
namespacing logic of ZF1 and the native PHP
• Hypertext Application Language (HAL) to offer namespace usage of ZF2. So we decided to set up
in-response links and resources Apigility on its own and bootstrap our ZF1 application
• selective HTTP verbs (GET, POST, PUT, DELETE, into the API manager. That worked out a lot better.
PATCH, etc.) access control
• application versioning through URI routes (e.g. / Getting Apiglity was easy. There are multiple ways
v1/user/1234) or through HTTP headers to install it, including from a release .tar file or using
• normalization and content validation, composer. All we needed to do was use the following

www.phparch.com January 2016 | 19


Build APIs on Existing Web Applications with Apigility

command to get the sources:

cd /path/to/workspace
curl -sS https://apigility.org/install | php Apigility Welcomes You FIGURE 3
After installation, Apigility was
launched on the built-in PHP web
server running on port 8888, so all
you had to do was point your browser
to http://localhost:8888/ to see
the nice welcome screen of Apigility.

Note for Very Old PHP


If you run a PHP version below 5.4,
you need to define a virtual host for
your web server; for Apache, it would
look like the configuration in Listing 1.

For other web servers, LISTING 1


please consult that web
server’s documentation to 01. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
configure a virtual host listening on port 02. # Configuration for Apigility #
8888 so the examples in this article will 03. # File: /etc/apache/vhosts/apigility.conf #
be similar to your own setup. Make 04. # #
sure the Apigility directory and 05. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
underlying files are writeable by 06. # #
your web server! 07. # WARNING: THIS IS DEVELOPMENT CONFIGURATION, DO NOT USE #
08. # IN A PRODUCTION ENVIRONMENT!!! #
09. # #
Pulling in the Sources 10. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
11.
of Our Web App 12. # Define the listen directive to match the examples
Once we had Apigility up and running, 13. Listen 8888
we still needed to have the API manager 14.
reusing the logic we already build in our 15. # Ensure Apache listens for named requests at port 8888
original application. Since Apigility uses 16. NameVirtualHost *:8888
Composer for managing its required 17.
packages, we decided to have our 18. # Define the virtual host configuration
web app’s source code be pulled in the 19. <VirtualHost *:8888>
vendor directory. 20. ServerName apigility.local
21. ServerAlias www.apigility.local
First we’re going to make the 22.
installation of Apigility a Git project. 23. DocumentRoot "/path/to/apigility/public"
24.
cd /path/to/apigility 25. <Directory "/path/to/apigility/public">
git init 26. Options Indexes FollowSymlinks
27. AllowOverride All
There are various ways to pull our 28. Order allow,deny
application sources into the Apigility 29. Allow from all
project, but the easiest way for us was to 30. DirectoryIndex index.php
add our repository using gitmodules. 31. </Directory>
32.
33. ErrorLevel Info
34. ErrorLog /var/log/apache/apigility-error_log
35. CustomLog /var/log/apache/apigility-access_log common
36. </VirtualHost>

20 | January 2016 www.phparch.com


Build APIs on Existing Web Applications with Apigility

WARNING: This is a private repository! Do not try to pull it in; use your own application for the purpose of
following along.

git submodule add -f git@server:mvdam/theialive.git vendor/theialive

Avoiding Collisions
LISTING 2
Since our application was written
in Zend Framework 1 and Apigility is 01. <?php
based on Zend Framework 2, we need 02.
to make sure both applications are 03. // Define path to application directory
not colliding with each other, as both 04. defined('APPLICATION_PATH')
use APPLICATION_PATH to define the 05. || define('APPLICATION_PATH',
location of the application. 06. realpath(__DIR__ . '/application'));
07.
Simply change APPLICATION_PATH 08. // Define application environment
to APIGILITY_PATH in the 09. defined('APPLICATION_ENV')
public/index.php bootstrap file 10. || define('APPLICATION_ENV',
using sed. 11. (getenv('APPLICATION_ENV') ?
12. getenv('APPLICATION_ENV') : 'production'));
sed -i '' 's/APPLICATION_PATH/'. 13.
'APIGILITY_PATH/g' 14. // Ensure library/ is on include_path
public/index.php 15. set_include_path(implode(PATH_SEPARATOR, array(
16. realpath(APPLICATION_PATH . '/../library'),
Autoloading ZF1 17.
18. )));
get_include_path(),

We have imported our web application 19.


using gitmodules, but that doesn’t 20. require_once 'Zend/Session.php';
mean that our application will be 21. Zend_Session::start();
automatically autoloaded. We need to 22.
bootstrap our ZF1 application without 23. require_once 'Zend/Config/Ini.php';
running it. We can copy most of our 24. $config = new Zend_Config_Ini(
vendor/theialive/public/ 25. APPLICATION_PATH . '/configs/application.ini',
index.php except the run() part. We 26. APPLICATION_ENV,
call this loader zf1for2.php and save 27. array ('allowModifications' => true)
it in the directory vendor/theialive, 28. );
see Listing 2. 29.
30. if (file_exists(APPLICATION_PATH . '/configs/local.ini')) {
Now we need to have Apigility 31. $localConfig = new Zend_Config_Ini(APPLICATION_PATH
autoload our application, so in the 32. . '/configs/local.ini');
Apigility public/index.php file we 33. $config->merge($localConfig);
just add this line: 34. }
35. $config->setReadOnly();
require_once __DIR__ . 36.
'/../vendor/theialive/' . 37. /** Zend_Application */
'zf1for2.php'; 38. require_once 'Zend/Application.php';
39.
40. // Create application, bootstrap, and run
41. $application = new Zend_Application(
42. APPLICATION_ENV,
43. $config
44. );
45. $application->bootstrap();

www.phparch.com January 2016 | 21


Build APIs on Existing Web Applications with Apigility

Theialive UML Use Case FIGURE 5


Authentication
Setting Up Our
First Endpoint Authenticate
uses View
Dashboard
uses
Update Profile

Now that the preparation


is done, it’s time to build Time Registration
the REST API. There are
several things we can Register Time uses
reuse from our existing
uses
application: Staff Select Task Select Project

• authentication Add uses


• listing of projects Description
• creating and
updating projects
• listing of tasks
Authentication
• creating and
updating tasks uses View uses Manage
Authenticate
Dashboard Profiles
To give you a better idea
of how all the components
work together, have a look Time Registration
at this basic UML Use Case
Manage
diagram, see Figure 5. Reports uses
uses Manage
Let’s start with Manager Manage Tasks
Projects
listing our projects uses
first. When we go back to Retrieve KPTs
http://localhost:8888 we see
the Apigility welcome screen. We’re creating a
new API, so we click on the New API button to
get started.

A dialog window pops up where we can fill out the name of our API, which we will call “theialive”. We click on
the Create button to continue.

The API management window now appears, allowing us to define our API endpoints.

There are two options we can use: REST or RPC; we choose REST as we’re building direct services to our existing
business logic. We click on create a new one within the REST section of the window.

New API FIGURE 6

New API title FIGURE 7

22 | January 2016 www.phparch.com

Вам также может понравиться