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:
instead of the prettier:
# 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 “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.
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.
<response> <code>1</code> <data>Hello World</data> </response>