Blog

RESTful Services

Share:

Every system uses resources. These resources can be pictures, video files, Web pages, business information, or anything that can be represented in a computer-based system. The purpose of a service is to provide a window to its clients so that they can access these resources.

Below diagrams depicts how Rest API sits in between a resource (Database) and clients (iPhone, desktop and android devices and access resources as per client’s requests via requests and responses. inform the technical staff about the problem,

REST API

REST stands for Representational State Transfer. It is primarily used to build Web services that are lightweight, maintainable, and scalable. A service based on REST is called a RESTful service. REST is not dependent on any protocol, but almost every RESTful service uses HTTP as its underlying protocol.

REST can be explained as a way to access resources which lie in a particular environment. For example, you can have a server that hosts important documents, pictures and/or videos.

In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. We will study all these terminologies in detail in later sections.

A brief History:

Web services have really come a long way since its inception. In 2002, the Web consortium had released the definition of WSDL and SOAP web services. This formed the standard of how web services are implemented.

In 2004, the web consortium also released the definition of an additional standard called RESTful. Over the past couple of years, this standard has become quite popular and is being used by many of the popular websites around the world which include Facebook and Twitter.

Properties and Features of RESTful services

In general, RESTful services should have following properties and features:

  • Representations
  • Messages
  • URIs
  • Uniform interface
  • Stateless
  • Links between resources
  • Caching

Representations

The focus of a RESTful service is on resources and how to provide access to these resources.

A resource can consist of other resources. While designing a system, the first thing to do is identify the resources and determine how they are related to each other. Once we have identified our resources, the next thing we need is to find a way to represent these resources in our system.

Below are the ways to represent a resource:

JSON representation of a resource

XML representation of a resource

Messages

The client and service talk to each other via messages. Clients send a request to the server, and the server replies with a response. Apart from the actual data, these messages also contain some metadata about the message.

Let’s see how a HTTP request looks.

HTTP Request

An HTTP request has the format as shown below:

Following terminologies are used in the request:

<VERB> is one of the HTTP methods like GET, PUT, POST, DELETE, OPTIONS, etc.

<URI> is the URI of the resource on which the operation is going to be performed.

<HTTP Version> is the version of HTTP, generally “HTTP v1.1”.

<Request Header> contains the metadata as a collection of key-value pairs of headers and their values. These settings contain information about the message and its sender like client type, the formats client supports, format type of the message body, cache settings for the response, and a lot more information.

<Request Body> is the actual message content. In a RESTful service, that’s where the representations of resources sit in a message.

Sample POST request

URI

URI stands for Uniform Resource Identifier. One can classify URIs as locators (URLs), or as names (URNs), or as both.

A Uniform Resource Name (URN) functions like a person’s name, while a Uniform Resource Locator (URL) resembles that person’s street address.

HTTP Response

Below figure shows the format of an HTTP response:

Following are the terminologies used in the response:

<Response code> The server returns response code, which contains the status of the request. This response code is generally the 3-digit HTTP status code. The first number indicates which of them a code belongs to:

  • 1xx – informational
  • 2xx – success
  • 3xx – redirection
  • 4xx – client error
  • 5xx – server error

<Response Header> contains the metadata and settings about the response message.

<Response Body> contains the representation if the request was successful.

Actual response to a GET request

The response code 200 OK means that everything went well and the response message body contains a valid representation of the resource requested.

Addressing Resources

A resource can be traced using a URL. A URL has following format:

Example

Query Parameters in URI

The preceding URI is constructed with the help of a query parameter:

Methods (or Verbs) used in Request header:

GET is probably the most popular method on the Web. It is used to fetch a resource.

PUT is idempotent. No matter how many times you send a PUT request, the results will be same. It is also mandatory to specify the complete URI of the resource in a PUT method. This implies that the client should be able to construct the URI of a resource even if it does not yet exist on the server.

POST is not an idempotent method. Making a POST multiple times may result in multiple resources getting created on the server.

Difference between PUT and POST:

OPTIONS is used to get a list of allowed operations on the resource. For example consider the request:

The service after authorizing and authenticating the request can return something like:

The second line contains the list of operations that are allowed for this client.

HEAD returns only the response headers with an empty body. This method can be used in a scenario when you do not need the entire representation of the resource. For example, HEAD can be used to quickly check whether a resource exists on the server or not.

Statelessness

A RESTful service is stateless and does not maintain the application state for any client. A request cannot be dependent on a past request and a service treats each request independently.

A stateless design looks like so:

Each of these requests can be treated separately.

A stateful design, on the other hand, looks like so:

To process the second request, the server needs to remember the last PersonID that the client fetched.

Caching

Caching is the concept of storing the generated results and using the stored results instead of generating them repeatedly if the same request arrives in the near future. This can be done on the client, the server, or on any other component between them, such as a proxy server. Caching is a great way of enhancing the service performance, but if not managed properly, it can result in client being served stale results.

For example, a service providing stock market updates would keep the cache age limit to as low as possible or even turn off caching completely as this is a critical information and users should get the latest results all the time. On the other hand, a public picture repository whose contents do not change so frequently would use a longer caching age and slack caching rules.

Caching can be controlled using these HTTP headers:

Control headers are:

Plugins for REST APIs:

Firefox plugin

Rest Client:

https://addons.mozilla.org/en-US/firefox/addon/restclient/

Chrome plugin

Advanced Rest Client:

https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo

Security in RESTful services:

 There are three major methods of adding security to an API —

  • HTTP Basic Auth,
  • API Keys
  • OAuth.

Authentication is when an entity proves an identity. In other words, Authentication proves that you are who you say you are. This is akin to having an identification card – an item given by a trusted authority that the requester, such as a police officer, can use as evidence that suggests you are in fact who you say you are.

REST API Automation:

Libraries:

  • HTTP URL Connection
  • Rest Assured

Rest Assured

Rest-Assured is a Java based library 

https://github.com/rest-assured/rest-assured/wiki/Downloads

JSON:

JSON stands for JavaScript Object Notation. JSON is a human and machine readable format to represent data as Structured Data. It is one of the most used Data-Exchange formats.

JSON is a light weight format represented as pure text.

Example:

Below is a JSON example of two countries namely India and Nepal describing their temperatures and currencies.

HTTP GET Request:

HTTP POST Request:

Code:

HTTP GET Example:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.ProtocolException;

import java.net.URL;

import java.util.HashMap;

import java.util.Iterator;

import org.json.JSONException;

import org.json.JSONObject;

public class GET_WeatherExample {

         URL url = null;

         HttpURLConnection conn = null;

         String output;

         JSONObject myResponse;

         BufferedReader br = null;

         /**

          * @param args

          */

         public void openConnection() {

            // Initialize URL object

            try {

                        url = new URL(

                                       "http://restapi.demoqa.com/utilities/weather/city/Hyderabad");

            } catch (MalformedURLException e) {

                        e.printStackTrace();

            }

            // Get the URLConnection instance of URL

            try {

                        conn = (HttpURLConnection) url.openConnection();

            } catch (IOException e) {

                        e.printStackTrace();

            }

            // Set HTTP method

            try {

                        conn.setRequestMethod("GET");

            } catch (ProtocolException e) {

                        e.printStackTrace();

            }

            // Set Header Property

            conn.setRequestProperty("Accept", "application/json");

         }

         public void checkResponseCode() {

            try {

                        if (conn.getResponseCode() != 200) {

                                    throw new RuntimeException("Failed : HTTP error code : "

                                                            + conn.getResponseCode());

                        } else {

                                    System.out.println(conn.getResponseCode());

                        }

            } catch (IOException e) {

                        e.printStackTrace();

            }

         }

         public BufferedReader checkRequestHeaders() {

            try {

                        br = new BufferedReader(new InputStreamReader(

                                                (conn.getInputStream())));

            } catch (IOException e) {

                        e.printStackTrace();

            }

            System.out.println(conn.getHeaderField("Content-Type"));

            System.out.println(conn.getHeaderField("Server"));

            // System.out.println(conn.getHeaderField("Content-Encoding"));

            return br;

         }

         public String validateResponseReceived(BufferedReader br) {

            System.out.println("Output from Server .... \n");

            StringBuffer response = new StringBuffer();

            try {

                        while ((output = br.readLine()) != null) {

                                    response.append(output);

                        }

                        while ((output = br.readLine()) != null) {

                                    System.out.println(output);

                        }

                        br.close();

            } catch (IOException e) {

                        e.printStackTrace();

            }

            System.out.println(response.toString());

            return response.toString();

         }

         public void validateSpecificNodeValue(String nodeValueToSearch,

                        String response) {

            try {

                        myResponse = new JSONObject(response);

                        System.out.println("\n\n\nSearching particular Node JSON Response");

                        Iterator keys = myResponse.keys();

                        HashMap map = new HashMap();

                        while (keys.hasNext()) {

                                    String key = (String) keys.next();

                                    Object val = myResponse.get(key);

                                    map.put(key, val.toString());

                        }

                        // System.out.println("statusCode- "+myResponse.getJSONArray("result"));

                        System.out.println("Node" + nodeValueToSearch + " value:"

                                                + map.get(nodeValueToSearch));

            } catch (JSONException e) {

                        e.printStackTrace();

            }

         }

         public void closeConnection() {

            conn.disconnect();

         }

}

Runner Class:

import java.io.BufferedReader;

public class RunnerClass {

            /**

             * @param args

             */

            public static void main(String[] args) {

                        GET_WeatherDetails details = new GET_WeatherDetails();

                        // Scenario 1: Check Response code

                        details.createConnection();

                        details.checkResponseCode();

                        // Scenario 2: get Header properties

                        BufferedReader br =details.getHeaders();

                        String response = details.validateResponseReceived(br);

                        details.validateSpecificNodeValue("Humidity",response);

                        details.closeConnection();

            }

}
Related Articles
Categories
Latest Articles

Popular Courses

Google Reviews
  • review rating 4  Training provided by the trainers in DevLabs Alliance is completely awesome. Trainers are highly qualified in their areas with practical experience. Since it is 3 days training we have completely got the opportunity to have hands on.

    thumb Salaja K
    6/30/2019
  • review rating 4  It was good session, I left my training room with basic knowledge on all the tools. Tutors have great knowledge and experience on the tools. But three days is not enough time.

    thumb sairam shyamala
    6/30/2019
  • review rating 5  Training provided by the trainers here is completely awesome. Trainer is highly qualified in their areas with practical experience. Also amenities provided during training by institute is great

    thumb Abhishek Tripathi
    6/02/2019
  • review rating 4  Both trainers (Ravi and Naresh) were excellent in their approach. Session was less of a theory and more of a practical. And even the theory part was quite interesting. A bit issue with the volume of information which I had received in just a span of 2-3 days - it seemed a bit over-loaded. But overall, it has given me a great platform to take it forward from here!

    thumb Varenya Varshney
    6/02/2019
  • review rating 5  Excellent Training program. Training courses and trainers are very good. Trainer will explain you as many time you ask the question. Best thing is hands on based training. You learn by doing. Looking for more courses from here.

    thumb Vijay Kumar
    6/30/2019
$('.enrollbtn').on('click', function (){ $( "#announcement" ).tabs( "option", "active", 0 ); $(' a[href="#announcement"]').trigger('click'); });