Category Archives: Web

Basic API: Redirecting URLs

In the thetvdb.com-example we can see that the URL is formed as if that XML-file is stored in the data/series/267440/all/ subdirectory. This is not the case, much like it isn’t the case that all the articles in WordPress are stored in their own directories. Instead the server is most likely using a redirect mechanism using the .htaccess-file.

In our new basic API we’ll do the same thing. By placing a .htaccess-file in the “mediainfo/api” directory on our server we can tell the web server how to handle requests in that subdirectory. In this case the file will look like this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ../apihandler.php?path=$1&%{QUERY_STRING} [L]

The RewriteCond-lines tell us that if the requested filename is not a file (!-f) or a directory (!-d) we will redirect the request to ^(.*)$ ../apihandler.php?path=$1&%{QUERY_STRING} [L]. The $1 will contain the excess path, in this case “search/a movie title”, and the QUERY_STRING is the standard GET-variables (may in fact not be necessary, verify)

This is the first step in creating an API that looks clean. By splitting the path and removing the forward slash we can handle requests differently based on the fake directories being requested.

Designing a REST API from scratch

A REST API is “an architectural style consisting of a coordinated set of architectural constraints applied to components, connectors, and data elements, within a distributed hypermedia system”. It’s often used to share information using either a JSON or XML format, as seen in this example over at thetvdb.com.

Writing a small API from scratch requires a few things. First we need to figure out how to format the URL, then we have to create a PHP script that posts information (usually from a database) formatted in either XML or JSON. This script needs to accept part of the URL as a parameter, not unlike the traditional use of the $_GET variable. These basic tasks are good to start out with, and should result in a decent first attempt at an API. In followup-articles I’ll write about my experiences with the three topics.