Build Restful Web Services in PHP

RestFul Web Services are very known among web programmers.Using web service you can allow to different applications to communicate over the network in platform independent manner.

Here I am going to build simple CRUD RestFul web service using Slim Framework.

Rest Server Application

Rest Provider exposes uri to manage different resources.There are two application here one for Restful web service and other for RestClient which consumes RestFul web services.

Database Structure

Here is only one table products.See below sql queries.

CREATE TABLE IF NOT EXISTS `products` (
`ID` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `price` double NOT NULL,
  `qty` int(11) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

db.php

<?php
 $host="localhost"; 
$user="root"; $password=""; 
$dbName = "slim";
 $link = mysql_connect($host,$user,$password);
 mysql_select_db($dbName,$link); ?>

Load Slim Library

Download Slim Framework
There are following requests supported by Slim Framework.Here $app is object of Slim Class.

  • $app->get();
  • $app->post();
  • $app->put();
  • $app->delete();
  • $app->patch();

Response types can be defined by following methods.

  • For JSON response
    $app->response->headers->set(‘Content-Type’, ‘application/json’);
  • For XML response
    $app->response->headers->set(‘Content-Type’, ‘text/xml’);

Getting request parameter by following.

  • $var = $app->request()->post(‘parameter_name’);
  • $paramValue = $application->request->params(‘paramName’);
  • $json = $app->request->getBody();
    $data = json_decode($json, true);

index.php

<?php require "db.php";
 require 'Slim/Slim.php';
 \Slim\Slim::registerAutoloader();
 $app = new \Slim\Slim(); 
$app->get('/product/fetch/:id',function ($id) use ($app){
	 $sql  = "SELECT * FROM products WHERE ID=".$id;
	 $result = mysql_query($sql);
	 $array  = array();
	 while ($row = mysql_fetch_assoc($result)) {
		$array['product_id'] = $row['ID'];
		$array['title'] 	 = $row['title'];
		$array['price'] 	 = $row['price'];
		$array['qty'] 		 = $row['qty'];
	}
	 $app->response->headers->set('Content-Type', 'application/json');
	 echo json_encode($array);
});

$app->get('/product/list',function () use ($app){
	 $sql  = "SELECT * FROM products";
	 $result = mysql_query($sql);
	 $array  = array();
	 $products = array();
	 while ($row = mysql_fetch_assoc($result)) {
		$array['product_id'] = $row['ID'];
		$array['title'] 	 = $row['title'];
		$array['price'] 	 = $row['price'];
		$array['qty'] 		 = $row['qty'];
		$products[]  		 = $array;
	}
	 $app->response->headers->set('Content-Type', 'application/json');
	 echo json_encode($products);
});
$app->post('/product/add',function() use($app){ 
	$product_name = $app->request()->post('product_name');
	$price = $app->request()->post('price');
	$qty   = $app->request()->post('qty');
	$sql	= mysql_query("Insert into products set title='".$product_name."',price='".$price."'");
	
});

$app->post('/product/update',function() use($app){
	$product_name = $app->request()->post('product_name');
	$price = $app->request()->post('price');
	$qty   = $app->request()->post('qty');
	$id    = $app->request()->post('product_id');
	$sql	= mysql_query("UPDATE products set title='".$product_name."',price='".$price."' WHERE ID=".$id);
	
});
$app->GET('/product/delete/:id',function($id) use($app){
	
	$sql	= mysql_query("DELETE FROM products WHERE ID=".$id);
	
});

/**
 *Run the Slim application
 */
$app->run();
?>

Rest Client

This is other application which consumes the Rest web services.I’ve used Ajax request to make requests to Rest Server.

index.php

 
<h1>Rest Client by StartWithJava</h1>
    <h2>Add/Edit Product</h2>
    <form action="" method="post" id="frmProduct">
    <input type="hidden" name="product_id" id="product_id">
        <table>
            <tr>
                <td>Product Name</td>
                <td>
                    <input type="text" name="product_name" id="product_name">
                </td>
            </tr>
            <tr>
                <td>Price</td>
                <td>
                    <input type="text" name="price" id="price">
                </td>
            </tr>
            <tr>
                <td>Qty</td>
                <td>
                    <input type="text" name="qty" id="qty">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" name="submit" value="Submit">
                </td>
            </tr>
        </table>
    </form>
    <h3>Product List</h3>
    <table border="1" id="productlist" width="70%">
    <thead>
    <th>Product Id</th>
    <th>Title</th>
    <th>Price</th>
    <th>Qty</th>
    <th>Actions</th>
    </thead>
    </table>
    <script src="jquery.min.js"></script>
    <script>
    jQuery(document).ready(function(){
        jQuery.ajax({
            url:'http://www.startwithjava.com/SlimAPI/product/list',
            type:'GET',
            success:function(response)
            {
                jQuery.each(response, function (key, product) {
                    console.log(key);
                    var html = "<tr id='row_"+product.product_id+"'>";
                    html += "<td>"+product.product_id+"</td>";
                    html += "<td>"+product.title+"</td>";
                    html += "<td>"+product.price+"</td>";
                    html += "<td>"+product.qty+"</td>";
                    html += "<td><a href='javascript:void(0);' rel='"+product.product_id+"' class='edit'>Edit</a>";
                    html +="|<a href='javascript:void(0);' rel='"+product.product_id+"' class='delete'>Delete</a></td>";
                    html += "</tr>";
                    jQuery("#productlist").append(html);
                });
            }
        });
        jQuery("#frmProduct").submit(function(){
            var id = jQuery("#product_id").val();
            var url='http://www.startwithjava.com/SlimAPI/product/add';
            if(id!="" && id>0){
                url='http://www.startwithjava.com/SlimAPI/product/update';
             }
            
            jQuery.ajax({
            url:url,
            type:'POST',
            data:jQuery("#frmProduct").serialize(),
            success:function(response)
            {
                jQuery("#product_name").val("");
                jQuery("#price").val("");
                jQuery("#qty").val("");
                jQuery("#product_id").val("");
            }
        });
         return false;
            
        });
         jQuery(".edit").live("click",function(){
            var id = jQuery(this).attr("rel");
            jQuery.ajax({
                url:'http://www.startwithjava.com/SlimAPI/product/fetch/'+id,
                type:'GET',
                success:function(response)
                {
                    jQuery("#product_name").val(response.title);
                    jQuery("#price").val(response.price);
                    jQuery("#qty").val(response.qty);
                    jQuery("#product_id").val(response.product_id);
                }
          });
            
        });
         jQuery(".delete").live("click",function(){
            var id = jQuery(this).attr("rel");
            var x = confirm("Are you confirm to delete");
            if(x){
                jQuery.ajax({
                    url:'http://www.startwithjava.com/SlimAPI/product/delete/'+id,
                    type:'GET',
                    success:function(response)
                    {
                        jQuery("#row_"+id).remove();
                    }
                });
            }
            
        });
        
     });
        

    </script>

See demo of application

rest

Leave a Reply