Developing Rest APIs in PHP using the Zend Framework


Share/Save/Bookmark

Developing Rest APIs in PHP using the Zend Framework is as quick as a wink.
Lets begin with the installation and environment setup. I assume you are running OpenSolaris.

Step-1: Installation and Configuration of AMP [Note: skip this if you have already setup and configured AMP]

bash# su – root
bash# pkg refresh
bash# pkg install amp
bash# /usr/sbin/svccfg import /var/svc/manifest/network/http-apache22.xml
bash# /usr/sbin/svcadm enable http:apache22
bash# /usr/sbin/svccfg import /var/svc/manifest/application/database/mysql.xml
bash# /usr/sbin/svcadm enable mysql:version_50

Step-2: Installation and Configuration of Zend Framework.

bash# cd /usr/php/lib
bash# wget http://framework.zend.com/releases/ZendFramework-1.7.5/ZendFramework-1.7.5.tar.gz
bash# tar -xzf ZendFramework-1.7.5.tar.gz

Edit php.ini file and set the include_path variable to include Zend framework library path.

bash# vi /etc/php/5.2/php.ini

Add “include_path”, if it does not exists. If it is already set, just add path to the zend library at the end. Make sure to use “:” path separator.

include_path = “.:/usr/php/lib/ZendFramework-1.7.5/library”

bash# svcadm restart svc:/network/http:apache22

Step-3: Create Sample Database for Weather REST API.
Lets create the sample database for weather REST API.

bash# /usr/mysql/5.0/bin/mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.67 Source distribution
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer. 

mysql> create database weatherdb;
Query OK, 1 row affected (0.00 sec)

mysql>use weatherdb;
Database changed

create tbl_zip_temperature table using following query.
create table tbl_zip_temperature (zip_code char(5), day_highest_temp int, day_lowest_temp int, PRIMARY KEY (zip_code));

mysql> create table tbl_zip_temperature (
-> zip_code char(5),
-> day_highest_temp int,
-> day_lowest_temp int,
-> PRIMARY KEY (zip_code)
-> );
Query OK, 0 rows affected (0.00 sec) 

Lets dump in some dummy records with following queries.

insert into tbl_zip_temperature values(95035,67,52);
insert into tbl_zip_temperature values(95112,70,54);
insert into tbl_zip_temperature values(95032,70,50);

mysql> insert into tbl_zip_temperature values(95035,67,52);
Query OK, 1 row affected (0.00 sec) 

mysql> insert into tbl_zip_temperature values(95112,70,54);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tbl_zip_temperature values(95032,70,50);
Query OK, 1 row affected (0.00 sec)

Step-4: Create Weather REST API using Zend Framework Library.
Here we are all set to begin the coding.
Lets create the weather_rest.php file under the document root (/var/apache2/2.2/htdocs) with following code.

<?php

include_once ('Zend/Rest/Server.php');

function get_temperature($zipcode) {
//error_code=0 for Sucesss / error_code=1 for Failure
    $error_code = 0;
    $doc = new DOMDocument();
    $doc->formatOutput = true;
// Creating Responce Element
    $root_element = $doc->createElement("response");
    $doc->appendChild($root_element);
//Create MYSQL Connection
    $MYSQL_DB_IP = 'localhost';
    $MYSQL_DB_USER = 'root';
    $MYSQL_DB_PASS = '';
    $MYSQL_DB_NAME = 'weatherdb';
    $conn = new mysqli($MYSQL_DB_IP, $MYSQL_DB_USER, $MYSQL_DB_PASS, $MYSQL_DB_NAME);
    $sql = "select day_highest_temp, day_lowest_temp from tbl_zip_temperature where zip_code='" . $zipcode . "';";
    $result = $conn->query($sql);
    if ($result === false) {
        $error_code = 1;
    } else {
        if ($conn->affected_rows > 0) {
            $row = $result->fetch_assoc();
            $zip_element = $doc->createElement("zipcode");
            $zip_element->appendChild($doc->createTextNode($zipcode));
            $temp_high_element = $doc->createElement("tempHigh");
            $temp_high_element->appendChild($doc->createTextNode($row["day_highest_temp"]));
            $temp_low_element = $doc->createElement("templow");
            $temp_low_element->appendChild($doc->createTextNode($row["day_lowest_temp"]));
            $root_element->appendChild($zip_element);
            $root_element->appendChild($temp_high_element);
            $root_element->appendChild($temp_low_element);
        } else {
            $error_code = 1;
        }
    }
//Return status failed, if any error found.
    if ($error_code == 1) {
        $statusElement = $doc->createElement("status");
        $statusElement->appendChild($doc->createTextNode("failed"));
        $root_element->appendChild($statusElement);
    }
// Return status passed, if no error found
    else if ($error_code == 0) {
        $statusElement = $doc->createElement("status");
        $statusElement->appendChild($doc->createTextNode("passed"));
        $root_element->appendChild($statusElement);
    }
    return simplexml_load_string($doc->saveXML());
}

$server = new Zend_Rest_Server();
$server->addFunction('get_temperature');
$server->handle();
?> 

That’s all, you are done with creating REST API. Lets open the firefox, to test this API.
Type in following URL in the address bar and hit enter.
http://localhost/weather_rest.php?method=get_temperature&zipcode=95035

Output of the REST API call with the status passed

if you hit http://localhost/weather_rest.php?method=get_temperature&zipcode=95055, you will get the output as given below. There is no record for this zip code in the database.

Output of the REST API call with the status failed

if you hit http://localhost/weather_rest.php?method=get_temperature, without any argument, you will get the output as given below.

Output of the REST API call without proper argument

You can also consume this RESTfull API in your Java Application. I will blog about it in my next post.

For Detailed explanation on “Zend_Rest_Server”, visit Zend Framework – Programmer Reference Guide

Don’t forget to leave your feedback 🙂

Advertisements

2 thoughts on “Developing Rest APIs in PHP using the Zend Framework

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s