Tuesday, November 5, 2013

Simplest Apache/PHP REST API

On Fedora (17 in my case)
with apache/php installed and running

1) enable URL mapping and map the URL to the PHP target file for REST processing

edit
/etc/httpd/conf/httpd.conf
  make sure this line is in the file:
 LoadModule rewrite_module modules/mod_rewrite.so

and then add
   RewriteEngine On
   RewriteLogLevel 3
   RewriteRule ^/rest_test/simple/(.*)$ /var/www/siab/src/rest_test.php?num=$1


2) restart the service:
    sudo service httpd restart



3) create the PHP API target file

/var/www/siab/src/rest_test.php looks like this:

<?php
$num = $_GET['num'];
$myData = array('results' => $num);
echo json_encode($myData);
exit(0);
?>

in browser: localhost/rest_test/simple/3
outputs:
   {"results":"3"}


4) of course in reality you want to do a lot more than this (like return status codes, do backend processing, handle POST as well as GET) but these are the very basics in a nutshell

-----------------------

for optional parameters:

RewriteRule ^/rest_test/simple/([^/]+)/?([^/]*)/?([^/]*)/?$ /var/www/siab/src/rest_test.php?num=$1&num2=$2&num3=$3

<?php
$num = "";
$num2 = "";
$num3 = "";

if (isset($_GET['num']))
   $num = $_GET['num'];
if (isset($_GET['num2']))
   $num2 = $_GET['num2'];
if (isset($_GET['num3']))
   $num3 = $_GET['num3'];
$myData = array('num' => $num, 'num2' => $num2, 'num3' => $num3);
echo json_encode($myData);
exit(0);
?>