Basic example on RESTful webservices in php

Hope you are aware on basics of RESTful webservices in php..if not pls clickhere

Lets start up with a basic example on RESTful services. I would like to thank YRRHELP in youtube for providing best example on this..

First let me explain a basic difference between website and webservices. I too have the same doubt before i review YRR tutorial..he explained in detail..let me start with that..

Difference between Website & Webservices:

Website will be requested by humans and response will show in HTML

Webservices: In most of the cases, request will be done by programs and response will be generated in XML or Json

This webservices is widely used to communicate between heterogeneous system and platform like PHP,Windows and anyother platforms can communicate to java/android.

Example:

Lets start up with a basic example like, if you call up for a book(C/Java) in an URL should display its price in JSON format.

02-04-2014 19-50-59

From the above pic you can notice that if i type “”C” it should display its price..similarly if i type “java” it should display java book price..

Here everything is coded in program and if you type some parameter it will display that desired result. This how webservices works..replace book name with city name and price with temperature will display the temperature of the city. This is the best real world example which i can explain.

Now lets peek into the code.. ūüėČ

1. create a folder in wamp server with name rest

2. create a index.php file

3. create a functions.php file

4. create a htaccess file

Now just copy the code from below..then save and run ūüôā

index.php

<?php

// process client request via URL
header(“content-type:application/json”);
include(“functions.php”);
if(!empty($_GET[‘name’]))
{
$name=$_GET[‘name’];
$price = get_price($name);
if(empty($price))
deliver_response(200,”book not found”,NULL);
else
deliver_response(200,”book found”,$price);
}
else
deliver_response(400,”Invalid request”,NULL);

function deliver_response($status,$status_message,$data)
{
header(“HTTP/1.1 $status $status_message”);
$response[‘status’]=$status;
$response[‘status_message’]=$status_message;
$response[‘price’]=$data;
$json_response = json_encode($response);
echo $json_response;
}

?>

functions.php

<?php
function get_price($find)
{
$books = array(“java”=>299,”c”=>348,”php”=>267);

foreach($books as $book=>$price)
{
if($book == $find)
{
return $price;
break;
}
}
}

?>

.htaccess

options +FollowSymlinks
RewriteEngine On

RewriteRule ^([a-zA-Z-]*)$ index.php?name=$1 [nc,qsa]

I hope by this time your brain is running with a doubt where comes this htaccess to live?? good question..let me explain with an image..

It will be very difficult to call up with parameters like below…

02-04-2014 19-50-59

Hence by using htaccess we can do like below..

02-04-2014 19-59-17

 

clickhere to know more about htaccess

References:

What Are RESTful Web Services?

RESTful web services¬†are built to work best on the Web. Representational State Transfer (REST) defines a set of architectural principles by which you can design Web services that focus on a system’s resources, including how resource states are addressed and transferred over HTTP by a wide range of clients written in different languages.In the REST architectural style, data and functionality are considered resources and are accessed using¬†Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.

The following principles encourage RESTful applications to be simple, lightweight, and fast:

  • Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery. See¬†The¬†@Path¬†Annotation and URI Path Templates¬†for more information.
  • Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations:¬†PUT,¬†GET,¬†POST, and¬†DELETE.¬†PUTcreates a new resource, which can be then deleted by using¬†DELETE.¬†GET¬†retrieves the current state of a resource in some representation.¬†POSTtransfers a new state onto a resource. See¬†Responding to HTTP Methods and Requests¬†for more information.
  • Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. See¬†Responding to HTTP Methods and Requests¬†and¬†Using Entity Providers to Map HTTP Response and Request Entity Bodies¬†for more information.
  • Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction. See¬†Using Entity Providers to Map HTTP Response and Request Entity Bodies¬†and ‚ÄúBuilding URIs‚ÄĚ in the JAX-RS Overview document for more information.

You can download Oreilly book here

Learn rest in online..clickhere

 

What are webservices

In simple words, webservices will establish a good mode of communication with other servers. Lets say like this, we have temperature widgets everywhere(android,ios,windows etc etc). Now you want to display temperature in your widgets..will you code everywhere to show the temperature? its a very bad idea..instead you can easily call up some webservices through api’s where your api will contact to yahoo temperature server and display temperature. Here yahoo server will have a kind of method in public where receives parameters from different clients and then process and send back responses to the websites through webservices. This is how webservices will work..the same procedure will follow for cricket score updates, currency updates etc etc. Hope this is clear to get an basic idea of webservices..

web service is a method of communication that allows two software systems to exchange this data over the internet. The software system that requests data is called a service requester, whereas the software system that would process the request and provide the data is called a service provider.

Different software might be built using different programming languages, and hence there is a need for a method of data exchange that doesn’t depend upon a particular programming language. Most types of software can, however, interpret XML tags. Thus web services can use XML files for data exchange.

Rules for communication between different systems need to be defined, such as:

  • How one system can request data from another system
  • Which specific parameters are needed in the data request
  • What would be the structure of the data produced. Normally, data is exchanged in XML files, and the structure of the XML file is validated by an .xsd file.
  • What error messages to display when a certain rule for communication is not observed, to make¬†troubleshooting¬†easier

All of these rules for communication are defined in a file called WSDL (Web Services Description Language), which has the extension .wsdl.

Web services architecture: the service provider sends a WSDL file to UDDI. The service requester contacts UDDI to find out who is the provider for the data it needs, and then it contacts the service provider using the SOAP protocol. The service provider validates the service request and sends structured data in an XML file, using the SOAP protocol. This XML file would be validated again by the service requester using an XSD file.

A directory called UDDI (Universal Description, Discovery and Integration) defines which software system should be contacted for which type of data. So when one software system needs one particular report/data, it would go to the UDDI and find out which other system it can contact for receiving that data. Once the software system finds out which other system it should contact, it would then contact that system using a special protocol called SOAP (Simple Object Access Protocol). The service provider system would first of all validate the data request by referring to the WSDL file, and then process the request and send the data under the SOAP protocol.