DevLabs Alliance - WhatsApp
DevLabs Alliance Logo

Home / Blogs /RESTful Services

RESTful Services

Admin

2023-09-08

DevLabs Alliance Blogs

0 mins read

RESTful Services


83181694597572601

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,

2941694597613998

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

88871694597643137

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:

6981694597675684

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

97091694597702158

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:

9691694597728768

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

341694597750282

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:

74531694597786465


Example

69181694597819235


Query Parameters in URI


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

36811694597835817

Methods (or Verbs) used in Request header:

34851694598058484

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:

78961694598140131

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

68931694598262288

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

33661694598303917

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:

47401694598348973

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:

16721694598390773

Control headers are:

99511694598419403

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.


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.

10191694598454996

HTTP GET Request:

9621694598475445

HTTP POST Request:

73941694598496534

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();

            }

}

Know Our Author

DevLabs Alliance Author Bio

Admin


DevLabs Alliance TwitterDevLabs Alliance LinkedInDevLabs Alliance Instagram

Author Bio

DevLabs Alliance conducts career transformation workshops & training in Artificial Intelligence, Machine Learning, Deep Learning, Agile, DevOps, Big Data, Blockchain, Software Test Automation, Robotics Process Automation, and other cutting-edge technologies.

INQUIRY

Want To Know More


Email is valid



Phone


By tapping continuing, you agree to our Privacy Policy and Terms & Conditions

“ The hands-on projects helped our team put theory into practice. Thanks to this training, we've achieved seamless collaboration, faster releases, and a more resilient infrastructure. ”
DevLabs Alliance Blogs Page Review
Vijay Saxena

SkillAhead Solutions

DevLabs Alliance Footer section
DevLabs Alliance LinkedIn ProfileDevLabs Alliance Twitter ProfileDevLabs Alliance Facebook ProfileDevLabs Alliance Facebook Profile
DevLabs Alliance Logo

Gurgaon

USA

1603, Capitol Avenue, Suite 413A, 2659, Cheyenne, WY 82001, USA

DevLabs Alliance ISO 9001

DevLabs Alliance Footer SectionDevLabs Alliance Footer SectionDevLabs Alliance Footer SectionDevLabs Alliance Footer SectionDevLabs Alliance Footer SectionDevLabs Alliance Footer SectionDevLabs Alliance Footer SectionDevLabs Alliance Footer Section

`Copyright © DevLabs Alliance. All rights Reserved`

|

Refund & Reschedule Policy

Privacy Policy

Terms of Use