Consuming PHP Zend Rest API in Java


In my last Weblog entry, I described the steps on developing Rest API in PHP using Zend Framework.

Now we have Rest API ready to be consumed by the client. Let consume it using Java Client.

Before beginning the coding part, we need to download following library.

The Jakarta Commons HttpClient 3.1 Library

Apache Commons Logging Library

Apache Commons Codec Library

First of all lets create the new NetBeans project. Select “java” from the project categories and “java Application” from the projects list. Click Next, name your project as “zend_rest_client” and finally click Finish button.



Right click on the Library and Select the Property. Add downloaded Library files using “Add Jar/Folder”.


Click “OK” and then replace the content of Main.Java file with the following code.

package zend_rest_client;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/* @author divyen patel */

public class Main {

    public static void main(String[] args) throws IOException, SAXException {
        String str_REST_SERVER = "http://localhost";
        String str_Port = "80"; //Default Apache Port
        String str_rest_API_page = "weather_rest.php";
        String str_rest_method = "get_temperature";
        String str_rest_method_argument = "zipcode=95035";
        String str_rest_url = str_REST_SERVER + ":" + str_Port + "/" + str_rest_API_page + "?method=" + str_rest_method + "&" + str_rest_method_argument;
        System.out.println("Request URL:" + str_rest_url + "\n");
// Send GET request
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(str_rest_url);
        int statusCode = client.executeMethod(method);
        InputStream rstream = null;
        rstream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
        String line;
        String xmlString = "";
        while ((line = br.readLine()) != null) {
            xmlString = xmlString + line;
        System.out.println("Request Response:" + xmlString + "\n");
//Parsing XML Response
        DOMParser parser = new DOMParser();
        parser.parse(new InputSource(new StringReader(xmlString)));
        Document document = parser.getDocument();
        System.out.println("Parsing XML Response");
        if (document.getElementsByTagName("status").item(0).getTextContent().equals("passed")) {
            System.out.println("Status: Passed");
            System.out.println("zipcode:" + document.getElementsByTagName("zipcode").item(0).getTextContent());
            System.out.println("tempHigh:" + document.getElementsByTagName("tempHigh").item(0).getTextContent());
            System.out.println("templow:" + document.getElementsByTagName("templow").item(0).getTextContent());
        } else {
            System.out.println("Status: Failed");

Finally right click on the project and Build it. You may see some warnings stating “DOMParser is Sun proprietary API and may be removed in a future release”. You can ignore these warnings.

Run the project and see the output in the IDE


You can also test it in the terminal console, using “java -jar <location of the jar file>”


If you have any better solution for consuming REST API in Java, please share with me. I am egar to learn it.

Developing Rest APIs in PHP using the Zend Framework


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
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.


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");
//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");
            $temp_high_element = $doc->createElement("tempHigh");
            $temp_low_element = $doc->createElement("templow");
        } else {
            $error_code = 1;
//Return status failed, if any error found.
    if ($error_code == 1) {
        $statusElement = $doc->createElement("status");
// Return status passed, if no error found
    else if ($error_code == 0) {
        $statusElement = $doc->createElement("status");
    return simplexml_load_string($doc->saveXML());

$server = new Zend_Rest_Server();

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.

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 🙂

Install and configure libssh2 and ssh2 PECL module with AMP on OpenSolaris

Detailed information on libssh2 and SSH2 PECL module is available on

libssh2 –

SSH2 PECL Module –

Installing AMP on OpenSolaris is quite easy. below are the
steps [1-4]
for AMP stack installation.

[ Step:1 ]

-bash-3.2# pkg refresh

[ Step:2

-bash-3.2# pkg install amp
13/13   1633/1633 331.59/331.59


[ Step:3 ]

-bash-3.2# /usr/sbin/svccfg import
-bash-3.2# /usr/sbin/svcadm enable http:apache22

[ Step:4 ]

-bash-3.2# /usr/sbin/svccfg import
-bash-3.2# /usr/sbin/svcadm enable mysql:version_50

before we begin
downloading libssh2 from sourceforge. We need to have
gcc compiler installed to compile and build libssh2 library.

[ Step:5 ]

-bash-3.2# pkg install gcc-dev
18/18   2797/2797 105.65/105.65


[ Step:6 ]

Download and extract libssh2 distribution.

-bash-3.2# cd /usr/src
-bash-3.2# wget
-bash-3.2# gunzip libssh2-0.18.tar.gz
-bash-3.2# tar xvf libssh2-0.18.tar

[ Step:7 ]

build and install libssh2

-bash-3.2# cd libssh2-0.18
-bash-3.2# ./configure
-bash-3.2# make all install

Next we need to link
libssh2 and PHP with the SSH2 PECL module.

[ Step:8 ]

-bash-3.2# cd /usr/src
-bash-3.2# wget
-bash-3.2# gunzip ssh2-0.10.tgz
-bash-3.2# tar xvf ssh2-0.10.tar

-bash-3.2# cd ssh2-0.10

[ Step:9 ]

edit ssh2.c and change
following if condition

#if LIBSSH2_APINO < 200412301450


#if LIBSSH2_VERSION_NUM < 0x001000

Save the file and execute phpize to prepare the build environment for
the ssh2 PHP extension.

[ Step:10 ]

-bash-3.2# pwd
-bash-3.2# /usr/php5/bin/phpize
Configuring for:
Zend Module Api No:     
Zend Extension Api No:   220060519

[ Step:11 ]

-bash-3.2# pwd

-bash-3.2# ./configure –with-ssh2
-bash-3.2# make
-bash-3.2# make install
Installing shared extensions:    

[ Step:12 ] module is now installed. We can modify the php.ini
file and make sure the module gets loaded by php.

-bash-3.2# vi /etc/php5/5.2.4/php.ini
under Dynamic Extensions section

restart the apache to and load the SSH2 php extension.

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

how to setup facebook php client library on Amazon EC2 AMP AMI

before you begin, have a quick look at the opensolaris AMP AMI(Amazon Machine Images) catalog

Following are the steps for setting up facebook application development platform on amazon ec2 AMP AMI.

[ step 1]
Launch ec2 instance using the AMI ID (ami-45f1152c) and get the instance id

bash # ec2-run-instances -k <your-keypair> ami-45f1152c

[ step 2]
get the public dns address of the instance using the instance id

bash # ec2-describe-instances <i-xxxxxxxx>

[ step 3]
make ssh connection to the instance.

bash # ssh -i <keypair file>

[ step 4]
download Official PHP client library from

bash # cd /var/apache2/2.2/htdocs/
bash # wget

[ step 5]
extract the platform library and place it at appropriate location

-bash # pwd
bash # gunzip facebook-platform.tar.gz
bash # tar -xf facebook-platform.tar
bash # rm facebook-platform.tar
bash # cd facebook-platform/
bash # mv client/ facebookphp/
bash # mv facebookphp/ /usr/lib/

[ step 5]

make necessary changes in the php.ini file located at /etc/php5/5.2/php.ini
add “/usr/lib/facebookphp” path in the include_path variable.

after the change it should look like this

include_path = ".:/var/php/5.2/pear:/usr/lib/facebookphp"

enable the short_open_tag, so that you can run sample facebook application correctly without any error.

after the change it should look like

short_open_tag = On

[step 6]

restart the apache to apply the changes done in the php.ini file.

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

[step 7]

arrange directories and perform clean up.

bash # cd /var/apache2/2.2/htdocs/facebook-platform
bash # mv footprints/ ../
bash # mv README ../footprints/
bash # cd ..
bash # pwd
bash # rm -rf facebook-platform/

[step 8]
change the include path in the sample footprint application as we no longer require relative path for the client library.Library path is already included within the php.ini file.

bash # cd footprints/
bash # vi index.php


// the facebook client library
include_once '../client/facebook.php';


// the facebook client library
include_once 'facebook.php';

[step 9]

facebook php client library is now installed and necessary changes has been applied to the sample footprint application.

follow the Readme file located at /var/apache2/2.2/htdocs/footprints/README to begin testing facebook application on amazon ec2.