Tag Archives: web development

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.