Mark Roland

a portfolio of art, design and technology

PHP API Template

November 14th, 2012

http://markroland.com/blog/restful-php-api/

Media: None

Tags:

Tutorial

How to Build a RESTful API Web Service with PHP

When I built my new online portfolio, I knew I wanted to create a RESTful API to easily access my data. Here’s how I did it.

I started developing my first API nearly 2 years ago. At that time I couldn’t find any simple examples, so I reverse engineered my experiences as a user of the Twitter and Flickr APIs. Over the years I have refined and distilled my API “template” so that I can add a web service to a site with minimal effort.

After I started writing this post I read “Create Your API with Restler” by Richard Askew in the December 2012 issue of .Net magazine. This is a really good article that confirms many of the techniques that I have been doing and have included in my sample code. Like many of the other API “How To” articles I’ve seen, this article relies on a library of dense code. That’s not a bad thing, but I think there’s a lot to be said for the simplicity of a single script with no included files, especially when learning something for the first time. With that in mind, I’m presenting this post as a simple, startup template for creating a RESTful API using PHP and no additional libraries.

As I started, it was simple enough to create some web service endpoints that would return data, but it took me a while to refine my code so that it would do things like set the correct HTTP Content-Type header, return useful HTTP response codes and provide multiple data formats. Taking what I have learned as I developed four similar web services, I have distilled my API script into four major parts: Initialization, Authorization, Request Processing and Response Delivery.

Set Up Your API Development Environment

The API environment is composed of 2 files, an application script (index.php) and a URL redirection file (.htaccess). The URL redirector will allow users to connect to the API using pretty URLs. The .htaccess file requires the mod_rewrite module on an Apache server. The API can still work if mod_rewrite is not available, but URLS will need to be formatted like:

“/api/?method=hello&format=json”

instead of the prettier:

“/api/hello.json”.

.htaccess:

# Turn on the rewrite engine
Options +FollowSymlinks
RewriteEngine on

# Request routing
RewriteRule ^([a-zA-Z_-]*)\.(html|json|xml)?$   index.php?method=$1&format=$2 [nc,qsa]
    

Step 1: Initialization

The first part of the API application script (index.php) is basic initialization. This part of the script defines the API’s settings, such as whether a secure HTTPS connection is required and whether the API is username and password protected. Additionally, the API initialization will define the API response codes. Finally, the initialization contains a function definition for the “deliver_response” function. This function controls the HTTP response codes, sets the Content-Type header and formats the data as JSON, XML or HTML. The “deliver_response” function is described in more detail in Step 4.

Step 2: Authorization

Authorization is an option that can be used to restrict access to the web services. This part of the code contains two “if” statements that optionally perform security tests based on the settings in Step 1. An advantage of requiring users to connect using HTTPS requests is that your data will be sent using encryption. This could be necessary if the web service is sending sensitive or personal information. The second “if” statement tests for the existence and authentication of a username and password.

Step 3: Process Request

The third step of the web service script is the meat of the API. This is where the the requested data is gathered by the application. In this example, the response data is simply a predefined “Hello World” message, but this could easily be replaced with code to retrieve information from a database or any other source, even another API! An API status code is also defined, as is an HTTP status code.

Step 4: Deliver Response

The final action of the web service script is to deliver a response in the format defined in the HTTP request. This API templates supports 3 different formats: JSON, XML and HTML. When I first started working with web services I thought XML was amazing because it was human-readable and could be formatted to meet any application’s needs. Unfortunately, the human-readiblity of XML means that it is more difficult to parse programmatically. On the other hand, PHP and JavaScript have such simple parsing options for JSON, that I would now be hard-pressed to choose formatting data using anything other than JSON. Returning the results as plain HTML can be beneficial in some cases, so I’ve included that option, too.

The “deliver_response” function first defines several basic HTTP response codes. After the response codes are defined, the data is formatted according to the value of the “format” variable in the request’s query string. The JSON response is complete, however the XML and HTML responses are only complete for simple string responses, and are not currently designed to handle arrays or data objects. You will want to tailor these to your specific needs.

Here is the complete index.php script.

index.php:

Conclusion

There you have it, a simple PHP API Web Service script. This is just a shell that can be filled in with your specific application needs. I hope you find it as useful as I have. If you have any questions or comments you can reach me on twitter @rolandojones.

Here are sample some endpoints and their responses.

http://markroland.com/project/php-api-template/demo/hello.json

        {"code":1,"status":200,"data":"Hello World"}
    

http://markroland.com/project/php-api-template/demo/hello.html

        Hello World
    

http://markroland.com/project/php-api-template/demo/hello.xml

        <response>
        <code>1</code>
        <data>Hello World</data>
        </response>
    
portrait