Tuesday, March 19, 2019

RESTful Web services


SOAP Vs REST


SOAP – SOAP is a protocol which was designed before REST and came into the picture. The main idea behind designing SOAP was to ensure that programs built on different platforms and programming languages could exchange data in an easy manner.


REST – This was designed specifically for working with components such as media components, files, or even objects on a particular hardware device. Any web service that is defined on the principles of REST can be called a RestFul web service. A Restful service would use the normal HTTP verbs of GET, POST, PUT and DELETE for working with the required components.




    SOAP

    REST
    • SOAP stands for Simple Object Access Protocol

    • REST stands for Representational State Transfer

    • SOAP is a protocol. SOAP was designed with a specification. It includes a WSDL file which has the required information on what the web service does in addition to the location of the web service.

    • REST is an Architectural style in which a web service can only be treated as a RESTful service if it follows the constraints of being
    1.   Client Server
    2.   Stateless
    3.   Cacheable
    4.   Layered System
    5.   Uniform Interface

    • SOAP cannot make use of REST since SOAP is a protocol and REST is an architectural pattern.

    • REST can make use of SOAP as the underlying protocol for web services, because in the end it is just an architectural pattern.

    Resource-oriented Architecture
A resource-oriented architecture (ROA) is the structural design supporting the internetworking of resources. A resource, in this context, is any entity that can be identified and assigned a uniform resource identifier (URI).

In information technology, architecture refers to the overall structure of an information system and the interrelationships of entities that make up that system. ROA is considered a RESTful architecture. REST (representational state transfer) is defined by Roy Fielding, co-author of the HTTP specification and co-founder of the Apache HTTP server project, as an architectural style that exploits the existing technology and protocols of the Web, including HTTP and XML.

Within the ROA concept, resources include not only IT infrastructure elements such as servers, computers and other devices, but also Web pages, scripts, and JSP/ASP pages, and other entities such as traffic lights.
Fielding’s doctoral dissertation, “Architectural Styles and the Design of Network-based Software Architectures,” identifies four essential concepts underlying the resource-oriented architecture:
  1. Resources
  2. Their names (URIs)
  3. Their representations
  4. The links between them.
and four properties:
  1. Addressability
  2. Statelessness
  3. Connectedness
  4. A uniform interface
“representations” in REST style


In REST-speak, a client and server exchange representations of a resource, which reflect its current state or its desired state. REST, or Representational state transfer, is a way for two machines to transfer the state of a resource via representations.










REST Architectural Constraints


REST stands for Representational State Transfer, a term coined by Roy Fielding in 2000. It is an architecture style for designing loosely coupled applications over HTTP, that is often used in the development of web services. REST does not enforce any rule regarding how it should be implemented at lower level, it just put high level design guidelines and leave you to think of your own implementation.
In my last employment, I designed RESTful APIs for telecom major company for 2 good years. In this post, I will be sharing my thoughts apart from normal design practices. You may not agree with me on a few points, and that’s perfectly OK. I will be happy to discuss anything from you with an open mind.
Let’s start with standard design specific stuff to clear what ‘Roy Fielding’ wants us to build. Then we will discuss my stuff which will be more towards finer points while you design your RESTful APIs.

Architectural Constraints

REST defines 6 architectural constraints which make any web service – a true RESTful API.
  1. Uniform interface
  2. Client–server
  3. Stateless
  4. Cacheable
  5. Layered system
  6. Code on demand (optional)

           Elements of REST style

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. REST encapsulates different activities of accessing and transferring representations into different connector types.
Components
In REST, the various software that interacts with one another are called components

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. REST identifies six data elements: a resource, resource identifier, resource metadata, representation, representation metadata, and control data.





                            RESTful API 



A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. The REST used by browsers can be thought of as the language of the internet. With cloud use on the rise, APIs are emerging to expose web services.




Web API

HTTP ‘APIs’ are becoming increasingly more important with the rise of the many devices in use today. Most mobile devices like phones and tablets run Apps that are using data retrieved from the Web over HTTP. Desktop applications are also moving in this direction with more and more online content and syncing moving into even traditional desktop applications. The pending Windows 8 release promises an app like platform for both the desktop and other devices, that also emphasizes consuming data from the Cloud.


Difference between MVC and Web API
There are many differences between MVC and Web API, including:
  • We can use the MVC for developing  the Web application that replies as both data and views but the Web API is used for generating the HTTP services that replies only as data.
  • In the Web API the request performs tracing with the actions depending on the HTTP services but the MVC request performs tracing with the action name.
  • The Web API returns the data in various formats, such as JSON, XML and other format based on the accept header of the request. But the MVC returns the data in the JSON format by using JSONResult.
  • The Web API supports content negotiation, self hosting. All these are not supported by the MVC.
  • The Web API includes the various features of the MVC, such as routing, model binding but these features are different and are defined in the "System.Web.Http" assembly. And the MVC features are defined in the “System.Web.Mvc" assembly.
  • The Web API helps the creation of RESTful services over the .Net Framework but the MVC does not support.


Implementations of JAX-RS include:

·         Apache CXF, an open source Web service framework.
·         Jersey, the reference implementation from Sun (now Oracle)
·         RESTeasy, JBoss's implementation.
·         Restlet.
·         WebSphere Application Server from IBM
·         WebLogic Application Server from Oracle, see notes.
        Everrest, Codenvy's Implementation.


Implementations of JAX-RS include:
·         Apache CXF, an open source Web service framework
·         Jersey, the reference implementation from Sun (now Oracle)
·         RESTeasyJBoss's implementation
·         Restlet
·         WebSphere Application Server from IBM:
·         Version 7.0: via the "Feature Pack for Communications Enabled Applications"
·         Version 8.0 onwards: natively
·         WebLogic Application Server from Oracle, see notes
·         Apache Tuscany (http://tuscany.apache.org/documentation-2x/sca-java-bindingrest.html), discontinued
·         Cuubez framework (http://www.cuubez.com)
·         Everrest, Codenvy's Implementation
·         Jello-Framework, Java Application Framework optimized for Google App Engine, including a powerful RESTful engine and comprehensive Data Authorization model.

RESTful Web Service - JAX-RS Annotations



Annotation
Package Detail/Import statement
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;





@GET
Annotate your Get request methods with @GET.
1
2
3
4
@GET
public String getHTML() {
  ...
}
@Produces
@Produces annotation specifies the type of output this method (or web service) will produce.
1
2
3
4
5
@GET
@Produces("application/xml")
public Contact getXML() {
  ...
}
1
2
3
4
5
@GET
@Produces("application/json")
public Contact getJSON() {
  ...
}
@Path
@Path annotation specify the URL path on which this method will be invoked.
1
2
3
4
5
6
@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.
1
2
3
4
5
6
7
@GET
@Produces("application/xml")
@Path("xml/{firstName}")
public Contact getXML(@PathParam("firstName") String firstName) {
  Contact contact = contactService.findByFirstName(firstName);
  return contact;
}
1
2
3
4
5
6
7
@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.
1
2
3
4
5
6
7
@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;
}
The example above returns a list of companies (with server side pagination) which can be displayed with rich clients implemented using Ext-js or jQuery. You can read more more about setting up ExtJS grid panel with remote sorting and pagination using Hibernate.
@POST
Annotate POST request methods with @POST.
1
2
3
4
5
6
@POST
@Consumes("application/json")
@Produces("application/json")
public RestResponse<Contact> create(Contact contact) {
...
}
@Consumes
The @Consumes annotation is used to specify the MIME media types a REST resource can consume.
1
2
3
4
5
6
7
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> update(Contact contact) {
...
}
@FormParam
The REST resources will usually consume XML/JSON@QueryParam annotation.
1
2
3
4
5
@POST
public String save(@FormParam("firstName") String firstName,
    @FormParam("lastName") String lastName) {
      ...
  }
@PUT
Annotate PUT request methods with @PUT.
1
2
3
4
5
6
7
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> update(Contact contact) {
...
}
@DELETE
Annotate DELETE request methods with @DELETE.
1
2
3
4
5
6
@DELETE
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> delete(@PathParam("contactId") int contactId) {
...
}




There are two main implementation of JAX-RS API.

  1. Jersey
  2. RESTEasy

Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides its own API that extend the JAX-RS toolkit. It provides additional features and utilities to further simplify RESTful service and client development. Jersey also exposes numerous extension SPIs so that developers may extend Jersey to best suit their needs.
RESTEasy provides various framework to build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.




Annotation
Description
Path
It identifies the URI path. It can be specified on class or method.
PathParam
Represents the parameter of the URI path.
GET
Specifies method responds to GET request.
POST
Specifies method responds to POST request.
PUT
Specifies method responds to PUT request.
HEAD
Specifies method responds to HEAD request.
DELETE
Specifies method responds to DELETE request.
OPTIONS
Specifies method responds to OPTIONS request.
FormParam
Represents the parameter of the form.
QueryParam
Represents the parameter of the query string of an URL.
HeaderParam
Represents the parameter of the header.
CookieParam
Represents the parameter of the cookie.
Produces
Defines media type for the response such as XML, PLAIN, and JSON etc. It defines the media type that the methods of a resource class or MessageBodyWriter can produce.
Consumes
It defines the media type that the methods of a resource class or MessageBodyReader can produce.
               




All resource methods can consume and produce content of almost any type. If you make a POST request to a URI, such as api/books, the REST API expects the HTTP body to contain a payload that represents the resource it should create.

This resource can be represented using any media type. Although typically, it will be represented in either, JSON or XML, but it could be plain text, binary or a custom format. It doesn’t matter, as long as there is a method in the resource class that can consume that media type.
In the header of the HTTP request, there is a content-type field that specifies the media type and on the other end, the server end, the resource class has a method annotated with the matching type.

So, for example: If a request has the content-type set to application/json the resource method that consumes this request is the method annotated with the same type, and likewise if the content type were application/xml the method annotated with MediaType APPLICATION_XML would handle that request.

Just as a method can consume a payload of a given type, it can produce a response payload of a specific media type too. In the case of a POST request, the created resource can be returned back to the client. Conventionally, it is returned back in the same format as it was received. So returns back as JSON, if it was POSTed in JSON format, nevertheless, this does not have to be the case.

There is another HTTP header that specifies the accepted return media-type and there is a matching annotation on the resource method also. Such a method would be annotated with the @Produces annotation and passed the MediaType APPLICATION_JSON.

So a full example would be an HTTP POST request with a content-type of JSON and an accept type of JSON, and the corresponding resource method would be annotated appropriately with both a @Consumes and @Produces annotation with the MediaType APPLICATION_JSON.








References:

https://whatis.techtarget.com/definition/resource-oriented-architecture-ROA

https://restfulapi.net/rest-architectural-constraints/


https://www.guru99.com/comparison-between-web-services.html#1










https://www.javatpoint.com/jax-rs-annotations-example


https://readlearncode.com/java-ee/java-ee-working-with-jax-rs-consumes-and-produces/