RESTful Web Service tutorial: An Introduction for beginners

restful-web-services-restREST is a term coined by Roy Fielding in his Ph.D. dissertation to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer. Representational State Transfer(REST), a software architecture style used in developing stateless web services. While this style may be used to describe any distributed framework that uses a simple protocol for data transmission and no other additional data transfer rules, the most common use of REST is on on the Web with HTTP being the only protocol used here. In REST each service (called “resource” in REST) is viewed as resource identified by a URL, and the only operations allowed are the HTTP – GET (Read), PUT (Update), POST(Create) and DELETE (Delete). You can find this style similar in SQL, thinking of a resource as equivalent to a Table. The main features and constraints of REST architectural style are:

  • Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.
  • Stateless: All REST resources are required to be stateless. The idea is that the application would be resilient enough to work between server restarts. However, it is not uncommon to see some RESTful web services save states between requests.
  • Caching: Caching is allowed, however it is required that “response to a request be implicitly or explicitly labeled as cacheable or non-cacheable”
  • As there is no interface definition (like in SOAP), it becomes mandatory for a Client and Server to have a mutual understanding of the messages being transmitted between them.

Given that every resource in a RESTful service is represented by a URL, it is easy to write a client for such a web service.

A lot of companies these days (including Amazon and Yahoo!) are exposing their web services in the form of REST resources. At a high level REST is pretty easy to understand, all you’re doing is exposing a web service in the form of a URL. Users can then query this URL, through HTTP methods like GET and POST. REST calls generally return some type of XML or Object Encoding like JSON.

REST in PHP

An example would be Yahoo!’s Geocoding API, with the following URL:


http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&street=701+First+Street&city=Sunnyvale&state=CA

You will get:

<Result precision="address">
   <Latitude>37.416384</Latitude>
   <Longitude>-122.024853</Longitude>
   <Address>701 FIRST AVE</Address>
   <City>SUNNYVALE</City>
   <State>CA</State>
   <Zip>94089-1019</Zip>
   <Country>US</Country>
</Result>

So Yahoo! exposes the Geocode URL and allows you to query this resource using URL parameters like appid and street. Dynamically building your URL to query a given resource is OK, generally that’s what people do, like the following:

$base = 'http://xml.amazon.com/onca/xml3';
$query_string = "";

$params = array( 'ManufacturerSearch' => "O'Reilly",
    'mode'  => 'books',
    'sort'  => '+salesrank',
    'page'  => 1,
    'type'  => 'lite',
    'f'     => 'xml',
    't'     => 'trachtenberg-20' ,
    'dev-t' => 'XXXXXXXXXXXXXX' ,
);

foreach ($params as $key => $value) {
    $query_string .= "$key=" . urlencode($value) . "&";
}

$url = "$base?$query_string";
$output = file_get_contents($url);

You may want to see the pear package HTTP Request for making REST calls, which among many things supports GET/POST/HEAD/TRACE/PUT/DELETE, basic authentication, proxy, proxy authentication, SSL, file uploads and more. Using this package, I got started on a simple wrapper class called RESTclient, which gives intuitive support for making REST resource calls.

So if we are going to use RESTclient to call the Geocode API above, following will be the source code:

<?php

require_once "RESTclient.php";

$rest = new RESTclient();

$inputs = array();
$inputs["appid"] = "YahooDemo";
$inputs["street"] = "701 First Street";
$inputs["city"] = "Sunnyvale";
$inputs["state"] = "CA";

$url = "http://api.local.yahoo.com/MapsService/V1/geocode/"
$rest->createRequest("$url","POST",$inputs);
$rest->sendRequest();
$output = $rest->getResponse();
echo $output;

?>

REST in Java

You may want to call the REST web service from Java. Following is the code for a simple Web Service client for the flickr web services interface.

package net.viralpatel.rest;

import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class FlickrClient {
	public static void main(String[] args) {
		String flickrURL = "http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value&api_key=[yourflickrkey]";

		try {
			SocketAddress addr = new InetSocketAddress("[proxy]", 9090);
			Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
			URL u = new URL("http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value&api_key=[yourflickrkey]");
			HttpURLConnection uc = (HttpURLConnection) u.openConnection(proxy);
			uc.setRequestProperty("Accept", "*/*");
			uc.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			uc.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
			uc.setRequestProperty("Keep-Alive", "300");
			uc.setRequestProperty("ucection", "keep-alive");
			String proxyUser = "[netUserId]";
			String proxyPassword = "[netPassword]";
			uc.setRequestProperty("Proxy-Authorization", "NTLM " + new sun.misc.BASE64Encoder().encode((proxyUser + ":" + proxyPassword).getBytes()));

			DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = docBuilder.parse(uc.getInputStream());

			System.out.println(doc.getDocumentElement().getTagName());

			System.out.println();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


9 Comments

  • amit 26 June, 2012, 17:55

    I want to make first web service any simple example, guide me any idea..

    • Sheldon 26 September, 2012, 13:51

      Could you please send any simple examples about web service to me ? Thanks in advance..
      sheldonz@yeah.net

  • Tejas 20 July, 2012, 20:41

    Hi Viral,

    I read your “RESTful Web Service tutorial: An Introduction for beginners” Artical. I am new in PHP. I got some work to call WCF based REST Service from PHP. I went through your examples but I am not able to find RESTclient.php file which you mentioned in second code snippet (require_once “RESTclient.php”;)

    Can you please send me that file or give me URL from where I can download that file and use it in my code.

  • G 6 August, 2012, 10:58

    Web service examples?

  • ag 27 December, 2012, 15:12

    i want create RESTful API using php, i want free demo plz sent via email amalg1991@gmail.com

  • Aurobinda Basu 16 May, 2013, 17:31

    Hello,
    I am new in webservice. Please provide me a simple example java webservice code and please send me a code explanation that how it works.. please in my e-mail id-basuarbind@gmail.com

  • pok 8 June, 2013, 21:38

    your examples are not rest, but rpc though xml, rest is hypertext driven, has links in response

  • Amrutha 24 December, 2013, 18:24

    Hi,

    CAn u give me and example of a restful webservice in java for consuming and producing a json

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *