RESTful Web services


 RESTful Web services

1. Message oriented communication Vs Resource oriented communication

Message Oriented Communication describes that involves the passing of data between applications using a communication channel that carries self-contained units of information (messages). In this communication environment, messages are generally sent and received asynchronously. Also senders and receivers are never aware of each other. Instead, they send and receive messages to and from the messaging system. It is the responsibility of the messaging system (MOM) to get the messages to their intended destinations.



A resource-oriented communication or architecture (ROA) represents blueprint of how supporting the inter networking of resources. A resource, in this context, is any entity that can be identified and assigned a uniform resource identifier (URI).

Identifies four essential concepts underlying the resource-oriented architecture:
  • Resources
  • Their names (URIs)
  • Their representations
  • The links between them.
and four properties:
  • Addressability
  • Statelessness
  • Connectedness
  • A uniform interface

2. Resource based nature of the REST style

Any RESTful API is mainly focused on the concept of the resource. A resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it. It is as same as the concept we known in object oriented programming, with the important difference that only a few standard methods are defined for the resource (corresponding to the standard HTTP GET, POST, PUT and DELETE methods), while an object instance typically has many methods.

Resources can be grouped into collections. Each collection contains only one type of resource, and unordered. Resources can also exist outside any collection. In this case, we refer to these resources as singleton resources. Collections are themselves resources as well.

Collections can exist globally, at the top level of an API, but can also be contained inside a single resource.
Some characteristics of RESTful API:-
  • Identified by URIs
  • Multiple URIs may refers to same resource but different according to the HTTP verb used (as like CRUD operation on same student resource)
  • Separate from their representations
  • Resource may be represented as request content type either JSON or XML etc.
A REST API commonly uses a response message’s entity body to help convey the state of a request message’s identified resource. REST APIs often employ a text-based format to represent a resource state as a set of meaningful fields. Today, the most commonly used text formats are XML and JSON.

XML, like HTML, organizes a document’s information by nesting angle-bracketed tag pairs. Well-formed XML must have tag pairs that match perfectly.

JSON uses curly brackets to hierarchically illustrates document’s information.

3. Meaning of “representations” in REST style

REST: Representational state transfer.

With REST, if you have a URL, then you have a resource. So, /programmers/Namespacinator is probably the address to a single programmer resource and /programmers is probably the address to a collection resource of programmers. So even a collection of programmers is considered one resource.

But we already build URLs that work like this on the web, so this is nothing new.

This is just a representation of the programmer resource. It happens to be in JSON, but the server could have represented the programmer in other ways, like in XML, HTML or even in JSON with a different format.

Representational State Transfer refers to transferring "representations". You are using a "representation" of a resource to transfer resource state which lives on the server into application state on the client.
Representation:- 
  • How resources get manipulated
  • Part of the resource state-transferred between client and server
  • Typically JSON or XML

4. Constraints of REST, indicating their use in the domain of web

Uniform Interface:- The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the architecture, which enables each part to evolve independently.

Stateless:- ne client can send multiple requests to the server; however, each of them must be independent, that is, every request must contain all the necessary information so that the server can understand it and process it accordingly.

Cacheable:- Because many clients access the same server, and often requesting the same resources, it is necessary that these responses might be cached, avoiding unnecessary processing and significantly increasing performance.

Client-Server:- The uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved.

Layered System:- A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. Layers may also enforce security policies.

Code-On-Demand:- This condition allows the customer to run some code on demand, that is, extend part of server logic to the client, either through an applet or scripts.

5. Identify contemporary examples of different types of implementations for the elements of REST style

The Representational State Transfer (REST) style is an abstraction of the architectural elements within a distributed hypermedia system. REST distinguishes three classes of architectural elements, they are:
  • Connectors
  • Components
  • Data Elements
Connectors:- Connectors represent the activities involved in accessing resources and transferring representations. Roles provide an interface for components to implement.
    Type & Ex:-
  • Client - HTTP library
  • Server - Web Server API
  • Cache - Browser cache
  • Resolver - bind (DNS lookup library)
  • Tunnel - SOCKS, SSL after HTTP CONNECT

Components:- In REST, the various software that interacts with one another are called components.
    Types & Ex:-
  • Origin Server - Apache httpd, Microsoft IIS
  • User Agent - Browser like Netscape Navigator etc
  • Gateway - Squid, CGI, Reverse Proxy
  • Proxy - CERN Proxy, Netscape Proxy, Gauntlet

Data Elements:- The key aspect of REST is the state of the data elements, its components communicate by transferring representations of the current or desired state of data elements.
    Types & Ex:-
  • Resource - Title of a movie from IMDb, A Flash movie from YouTube, Images from Flickr etc
  • Resource Identifier - Standardized format of URI:scheme://host:port/path?
  • Resource metadata - Source link, vary
  • Representation - Sequence of bytes, HTML document, archive document, image document
  • Representation metadata - Headers (media-type)
  • Control data - If-Modified-Since, If-Match

6. The API of RESTful web services using RESTful URLs

http://localhost:8080/UserManagement/rest/UserService/users - Gets the list of users.
http://localhost:8080/UserManagement/rest/UserService/users/1 - Gets the User of Id 1
http://localhost:8080/UserManagement/rest/UserService/users/2 - Inserts User with Id 2
http://localhost:8080/UserManagement/rest/UserService/users - Lists out the supported operations in a web service.
  1. Use nouns and NOT the verbs:- A lot of developers make this mistake. They generally forget that we have HTTP methods with us to describe the APIs better and end up using verbs in the API URLs. For instance, API to get all products should be   

    /products
  2. Use of right HTTP methods:- RESTful APIs have various methods to indicate the type of operation we are going to perform with this API —

    GET — To get a resource or collection of resources.
    POST — To create a resource or collection of resources.
    PUT/PATCH — To update the existing resource or collection of resources.
    DELETE — To delete the existing resource or the collection of resources.
  3. Use Plurals:- This topic is bit debatable. Some of people like to keep the resource URL with plural names while others like to keep it singular. For instance —

    /products
    /product

    I like to keep it plural since it avoids confusion whether we are talking about getting single resource or a collection. It also avoids adding additional things like attaching all to the base URL e.g. /product/all
  4. Use parameters:- Sometime we need to have an API which should be telling more story than just by id. Here we should make use of query parameters to design the API.

    /products?name=’ABC’ should be preffered over /getProductsByName
    /products?type=’xyz’ should be preferred over /getProductsByType
              package com.tutorialspoint;  

              import java.util.List;
              import javax.ws.rs.GET; 
              import javax.ws.rs.Path; 
              import javax.ws.rs.Produces; 
              import javax.ws.rs.core.MediaType;  
              @Path("/UserService") 

              public class UserService {  
                  UserDao userDao = new UserDao();  
                  @GET 
                  @Path("/users") 
                  @Produces(MediaType.APPLICATION_XML) 
                  public List<User> getUsers(){ 
                      return userDao.getAllUsers(); 
                  }  
              }

7. Pros and cons of using MVC for RESTful web service development, indicating the application of MVC in RESTful web service design

  • In Spring MVC, a controller can handle the requests for all HTTP methods, which is a backbone of RESTful web services. For example, you can handle a GET method to perform read operations, POST methods to create resources, PUT methods to update resources, and DELETE methods to remove resources from the server.
  • In the case of REST, the representation of data is very important and that's why Spring MVC allows you to bypass View-based rendering altogether by using the @ResponseBody annotation and various HttpMessgeConverter implementations. By using this, you can directly send a response to a client, e.g. the resource clients want and also in the format they want. See here to learn more about HttpMessageConvert and @ResponseBody annotation. 
  • The Spring 4.0 release added a dedicated annotation, @RestController, to make the development of RESTful web services even easier.
    If you annotate your controller class using @RestController instead of @Controller then Spring applies message conversations to all handler methods in the controller.
  • 4. One of the main differences between a REST web service and a normal web application is that the REST pass resource identifies data in the URI itself, e.g. /messages/101, while web applications normally use a query parameter, e.g.  /messages?Id=101.
  • Another key aspect of RESTful web services is Representation, meaning the same resource can be represented in different formats, i.e. JSON, XML, HTML, etc. Thankfully, Spring provides several view implementations and views resolvers to render data as JSON, XML, and HTML.
  • Similar to the @ResponseBody annotation, which is used for converting the response to the format client wants (by using HttpMessageConverts), Spring MVC also provides @RequestBody annotation, which uses HttpMethodConverter implementations to convert inbound HTTP data into Java objects passed into a controller's handler method.
Advantages:-
  • Faster development process
  • Support for asynchronous technique
  • Modification does not affect the entire model
  • MVC model returns the data without formatting
  • SEO friendly Development platform
Disadvantages:-
  • Increased complexity
  • Need multiple programmers
  • Knowledge on multiple technologies is required.

8. JAX-RS API and its implementations

JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013. JAX-RS uses annotations available from Java SE 5 to simplify the development of JAVA based web services creation and deployment. It also provides supports for creating clients for RESTful Web Services.

Hello.java
  1. package com.javatpoint.rest;  
  2. import javax.ws.rs.GET;  
  3. import javax.ws.rs.Path;  
  4. import javax.ws.rs.Produces;  
  5. import javax.ws.rs.core.MediaType;  
  6. @Path("/hello")  
  7. public class Hello {  
  8.   // This method is called if HTML and XML is not requested  
  9.   @GET  
  10.   @Produces(MediaType.TEXT_PLAIN)  
  11.   public String sayPlainTextHello() {  
  12.     return "Hello Jersey Plain";  
  13.   }  
  14.   // This method is called if XML is requested  
  15.   @GET  
  16.   @Produces(MediaType.TEXT_XML)  
  17.   public String sayXMLHello() {  
  18.     return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";  
  19.   }  
  20.   
  21.   // This method is called if HTML is requested  
  22.   @GET  
  23.   @Produces(MediaType.TEXT_HTML)  
  24.   public String sayHtmlHello() {  
  25.     return "<html> " + "<title>" + "Hello Jersey" + "</title>"  
  26.         + "<body><h1>" + "Hello Jersey HTML" + "</h1></body>" + "</html> ";  
  27.   }  
  28. }   

web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3. xmlns="http://java.sun.com/xml/ns/javaee"   
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  5. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
  6. id="WebApp_ID" version="3.0">  
  7.  <servlet>  
  8.     <servlet-name>Jersey REST Service</servlet-name>  
  9.     <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>  
  10.     <init-param>  
  11.         <param-name>jersey.config.server.provider.packages</param-name>  
  12.         <param-value>com.javatpoint.rest</param-value>  
  13.     </init-param>  
  14.     <load-on-startup>1</load-on-startup>  
  15.   </servlet>  
  16.   <servlet-mapping>  
  17.     <servlet-name>Jersey REST Service</servlet-name>  
  18.     <url-pattern>/rest/*</url-pattern>  
  19.   </servlet-mapping>  
  20. </web-app>   

9. Annotations in JAX-RS, explaining their use

@GET - Annotate your Get request methods with @GET.
@GET
public String getHTML() {
  ...
}

@Produces - @Produces annotation specifies the type of output this method (or web service) will produce.
@GET
@Produces("application/json")
public Contact getJSON() {
  ...
}

@Path - annotation specify the URL path on which this method will be invoked.
@GET
@Produces("application/xml")
@Path("xml/{firstName}")
public Contact getXML() {
  ...
}

@PathParam - We can bind REST-style URL parameters to method arguments using @PathParam annotation as shown below.
@GET
@Produces("application/json")
@Path("json/{firstName}")
public Contact getJSON(@PathParam("firstName") String firstName) {
  Contact contact = contactService.findByFirstName(firstName);
  return contact;
}

@QueryParam - Request parameters in query string can be accessed using @QueryParam annotation as shown below.
@GET
@Produces("application/json")
@Path("json/companyList")
public CompanyList getJSON(@QueryParam("start") int start, @QueryParam("limit") int limit) {
  CompanyList list = new CompanyList(companyService.listCompanies(start, limit));
  return list;
}

@POST - Annotate POST request methods with @POST.
@POST
@Consumes("application/json")
@Produces("application/json")
public RestResponse<Contact> create(Contact contact) {
...
}

@FormParam - The REST resources will usually consume XML/JSON for the complete Entity Bean. Sometimes, you may want to read parameters sent in POST requests directly and you can do that using @FormParam annotation. GET Request query parameters can be accessed using @QueryParam annotation.
@POST
public String save(@FormParam("firstName") String firstName,
    @FormParam("lastName") String lastName) {
      ...
  }

@DELETE - Annotate DELETE request methods with @DELETE.
@DELETE
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> delete(@PathParam("contactId") int contactId) {
...
}

10. Use and importance of “media type” in JAX-RS 

package com.javapapers.webservices.rest.jersey;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/helloworld")
public class HelloWorld {

 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public String sayPlainTextHello() {
  return "Hello World RESTful Jersey!";
 }

 @GET
 @Produces(MediaType.TEXT_XML)
 public String sayXMLHello() {
  return "<?xml version=\"1.0\"?>" + "<hello> Hello World RESTful Jersey"
    + "</hello>";
 }

 @GET
 @Produces(MediaType.TEXT_HTML)
 public String sayHtmlHello() {
  return "<html> " + "<title>" + "Hello World RESTful Jersey"
    + "</title>" + "<body><h1>" + "Hello World RESTful Jersey"
    + "</body></h1>" + "</html> ";
 }

}
Resources have representations. A resource representation is the content in the HTTP message that is sent to, or returned from the resource using the URI. Each representation that a resource supports has a corresponding media type. For example, if a resource is going to return content formatted as XML, you can use application/xml as the associated media type in the HTTP message.

JAX-RS provides @Consumes and @Produces annotations to declare the media types that are acceptable for a resource method to read and write.

In the retrieveSpecificBookInformation method example that follows, there is no request entity that is read. However, there is a response object that is returned. This object wraps a JAXB object that contains the entity information. Adding the @Produces annotation on the resource method with a media type of application/xml indicates that the resource method always returns an XML representation with a media type of application/xml.

Clients that have an Accept HTTP request header value compatible with the application/xml media type invoke the method correctly.

Clients that do not have an Accept HTTP header value compatible with the application/xml media type automatically receive a 406 Not Acceptable response status which indicates that the server cannot produce an acceptable response.

References

[1] Message Oriented Middleware (MOM) - https://www.oreilly.com/library/view/enterprise-service-bus/0596006756/ch05.html

[2] resource-oriented architecture (ROA) - https://whatis.techtarget.com/definition/resource-oriented-architecture-ROA

[3] RESTful API - https://restful-api-design.readthedocs.io/en/latest/resources.html


[4] REST: Resources and Representations  - https://symfonycasts.com/screencast/rest/rest

[5] Chapter 5. Representation Design - https://www.oreilly.com/library/view/rest-api-design/9781449317904/ch05.html

[6] What is REST? REST Architecture and REST Constraints - https://www.dineshonjava.com/what-is-rest-and-rest-architecture-and-rest-constraints/

[7] REST Architectural Constraints - https://restfulapi.net/rest-architectural-constraints/

[8] REST Architectural Elements and Constraints - http://mrbool.com/rest-architectural-elements-and-constraints/29339

[9] RESTful API Design — Step By Step Guide - https://hackernoon.com/restful-api-design-step-by-step-guide-2f2c9f9fcdbf

[10] An Introduction to API’s - https://restful.io/an-introduction-to-api-s-cee90581ca1b

[11] 7 Reasons to Use Spring MVC for Developing RESTful Web Services in Java - https://dzone.com/articles/7-reasons-to-use-spring-mvc-for-developing-restful

[12] RESTful Web Service - JAX-RS Annotations - http://www.techferry.com/articles/RESTful-web-services-JAX-RS-annotations.html

[13] Defining media types for resources in RESTful applications - https://www.ibm.com/support/knowledgecenter/cs/SSEQTP_8.5.5/com.ibm.websphere.base.doc/ae/twbs_jaxrs_defresource_mediatype.html

Thank you for reading till the end and see you on another blog post.



Comments

Popular posts from this blog

Tutorial 02 – Industry Practices and Tools 1 Article

THE CLIENT-SIDE DEVELOPMENT

RiWAs - Client-side development 2