Friday, 22 March 2019

RESTful WEB SERVICES

RESTful WEB SERVICES



A web service consists of a collection of open protocols and standards used for data exchange between applications or systems. Software applications written in different programming languages and running on different platforms may use web services to exchange data on computer networks such as the Internet, such as inter-process communication on a single computer.

What is rest architecture?


§  §  REST stands for REpresentational State Transfer. REST is web standard    based architecture and uses HTTP Protocol.

§        It revolves around resource where every component is a resource and a   resource are accessed by a common interface using HTTP standard   methods.

§    REST was first introduced by Roy Fielding in 2000.

§       In REST architecture, a REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML. JSON is the most popular one.

§      HTTP methods:
o   GET − Provides a read only access to a resource.
o   POST − Used to create a new resource.
o   DELETE − Used to remove a resource.
o   PUT − Used to update an existing resource or create a new resource.


Resource based nature of REST style
Resource

§      REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ Global IDs.

§      REST uses various representations to represent a resource where Text, JSON, XML. The most popular representations of resources are XML and JSON.

Representation of Resources

§     A resource in REST is a similar Object in Object Oriented Programming or is like an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the above said format and client can understand the same format.

§      Resource-Oriented Architecture is also RESTful. But REST is not an architecture: it’s a set of design criteria. You can say that one architecture meets those criteria better than another, but there is no one “REST architecture.”
Up to now, people have tended to mint one-off architectures as they design their services, according to their own understandings of REST. The most obvious outcome of this is the wide variety of REST-RPC hybrid web services that their creators claim are RESTful. I’m trying to put a stop to that by presenting a set of concrete rules for building web services that really will be RESTful. In the next two chapters I’ll even show simple procedures you can follow to turn requirements into resources. If you don’t like my rules, you’ll at least have an idea of what you can change and stay RESTful.
As a set of design criteria, REST is very general. In particular, it’s not tied to the Web. Nothing about REST depends on the mechanics of HTTP or the structure of URIs. But I’m talking about web services, so I explicitly tie the Resource-Oriented Architecture to the technologies of the Web. I want to talk about how to do REST with HTTP and URIs, in specific programming languages. If the future produces RESTful architectures that don’t run on top of the Web, their best practices will probably look similar to the ROA, but the details will be different. We’ll cross that bridge when we come to it.
The traditional definition of REST leaves a lot of open space, which practitioners have seeded with folklore. I deliberately go further than Roy Fielding in his dissertation, or the W3C in their standards: I want to clear some of that open space so that the folklore has room to grow into a well-defined set of best practices. Even if REST were an architecture, it wouldn’t be fair to call my architecture by the same name. I’d be tying my empirical observations and suggestions to the more general thoughts of those who built the Web.
My final reason for coming up with a new term is that “REST” is a term used in religious nerd wars. When it’s used, the implication is usually that there is one true RESTful architecture and it’s the one the speaker prefers. People who prefer another RESTful architecture disagree. The REST community fragments, despite a general agreement on basic things like the value of URIs and HTTP.
Ideally there would be no religious wars, but I’ve seen enough to know that wishing won’t end them. So I’m giving a distinctive name to my philosophy of how RESTful applications should be designed. When these ideas are, inevitably, used as fodder in wars, people who disagree with me can address aspects of the Resource-Oriented Architecture separate from other RESTful architectures, and from REST in general. Clarity is the first step toward understanding.
Meaning of “representations” in REST style

REST means the Representational State Transfer. So the Representation is the value/response of the Resource at a point in time based on the media-type. Resources can be manipulated only through their representations.

In REST API, resource is the concept which has representation associated with it** i.e. some response at a point in time. It means a function /api/v1/user/unsubscribe could also be the resource as the information is associated with it.
There might be the case when resource is mapped to empty representation. This particular scenario can be seen when client requests the resource identifier (URL) of the S3 bucket where it can put the object like images. AWS while creating resource identifier maps it to empty representation. Later client put the object at the location to make concrete representation of the resource.

Messages in RESTful Web Services

§       RESTful Web Services make use of HTTP protocols as a medium of communication between client and server. A client sends a message in form of a HTTP Request and the server responds in the form of an HTTP Response.

§  This technique is termed as Messaging. These messages contain message data and metadata i.e. information about message itself. 




§  A HTTP request has five major parts. They are,

o   Verb – This indicates the HTTP methods such as GET, POST, DELEET, PUT, etc.
o   URI – Uniform Resource Identifier (URI) to identify the resource on the server.
o   HTTP Version – This contains metadata for the HTTP Request message as a key value pair. For an example client type, format supported by the client, format of the message body, cache settings, etc.
o   Request Body – Message contain or Resource representation.


§      HTTP Response:

§  A HTTP Response has four major parts, they are,

o   Status/Response Code – This indicates the server status for the request resource. For example, 404 means resource not found and 200 means response is ok.
o   HTTP Version- This indicates the HTTP version. For example, HTTP v1.1.
o   Response Header -This contains metadata for the HTTP response message as key value pairs. For example, content length, content type, response date, server type, etc.
o   Response Body -   Response message content or resource representation.

REST Architectural Elements and Constraints

§  REST distinguishes three classes of architectural elements, they are:
o   Connectors
o   Components
o   Data Elements

REST architectural Elements.

§  Connectors:
o   Connectors represent the activities involved in accessing resources and transferring representations.
o   Roles provide an interface for components to implement.
o   REST encapsulates different activities of accessing and transferring representations into different connector types.
o   There are some types of connectors. They are,


§  Components:
o   In REST, the various software that interacts with one another are called components.
o   There are some types of components. Some of them are,


§  Data Elements
o   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.
o   REST identifies six elements: They are,


RESTful web services using RESTful URLs

Use RESTful service URLs

Under REST principles, a URL identifies a resource. The following URL design patterns are considered REST best practices:
·         URLs should include nouns, not verbs.
·         Use plural nouns only for consistency (no singular nouns).
·         Use HTTP methods (HTTP/1.1) to operate on these resources:
·         Use HTTP response status codes to represent the outcome of operations on resources.
Agencies should consistently apply RESTful design patterns for API URLs.

Versioning

Example of an API URL that contains a version number:
GET /v1/path/to/resource HTTP/1.1
Host: www.example.gov.au
Accept: application/json, text/javascript
An API URL may contain a version number.
See versioning for more details.


MVC for RESTful web service development, indicating the application of MVC in RESTful web service design
The Spring Web MVC module provides an implementation of the traditional Model View Controller pattern. While REST does not mandate the use of any specific pattern, using the MVC pattern is quite a natural fit whereby the RESTful resource or model is exposed through a controller. The view in our case will be a JSON representation of the model.
Without further ado, let's take a look at our first endpoint:
Copy
@RestController
@RequestMapping("/rooms")
public class RoomsResource {

  private final InventoryService inventoryService;

  public RoomsResource(InventoryService inventoryService) {
    this.inventoryService = inventoryService;
  }

  @RequestMapping(value = "/{roomId}", method = RequestMethod.GET)
  public RoomDTO getRoom(@PathVariable("roomId") String roomId) {
    RoomDTO room = ...
    // omitted for sake of clarity
    return room;
  }
}

Pros:
1) Faster development process: MVC supports rapid and parallel development. With MVC, one programmer can work on the view while other can work on the controller to create business logic of the web application. The application developed using MVC can be three times faster than application developed using other development patterns.
2) Ability to provide multiple views: In the MVC Model, you can create multiple views for a model. Code duplication is very limited in MVC because it separates data and business logic from the display.
3) Support for asynchronous technique: MVC also supports asynchronous technique, which helps developers to develop an application that loads very fast.
4) Modification does not affect the entire model: Modification does not affect the entire model because model part does not depend on the views part. Therefore, any changes in the Model will not affect the entire architecture.
5) MVC model returns the data without formatting: MVC pattern returns data without applying any formatting so the same components can be used and called for use with any interface.
6) SEO friendly Development platform: Using this platform, it is very easy to develop SEO-friendly URLs to generate more visits from a specific application.


Cons:
Disadvantages of MVC
1) Increased complexity
2) Inefficiency of data access in view
3) Difficulty of using MVC with modern user interface.
4) Need multiple programmers
5) Knowledge on multiple technologies is required.
6) Developer have knowledge of client side code and html code.


JAX-RS API
AX-RS: Java API for RESTful Web Services (JAX-RS) is a Java programming language API spec that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern. JAX-RS uses annotations, introduced in Java SE 5, to simplify the development and deployment of web service clients and endpoints.
From version 1.1 on, JAX-RS is an official part of Java EE 6. A notable feature of being an official part of Java EE is that no configuration is necessary to start using JAX-RS. For non-Java EE 6 environments a small entry in the web.xml deployment descriptor is required.

Implementations of JAX-RS:

·         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:
·         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.



 Annotations in JAX-RS
AX-RS provides some annotations to aid in mapping a resource class (a POJO) as a web resource. The annotations use the Java package javax.ws.rs. They include:
·         @Path specifies the relative path for a resource class or method.
·         @GET, @PUT, @POST, @DELETE and @HEAD specify the HTTP request type of a resource.
·         @Produces specifies the response Internet media types (used for content negotiation).
·         @Consumes specifies the accepted request Internet media types.
In addition, it provides further annotations to method parameters to pull information out of the request. All the @*Param annotations take a key of some form which is used to look up the value required.
·         @PathParam binds the method parameter to a path segment.
·         @QueryParam binds the method parameter to the value of an HTTP query parameter.
·         @MatrixParam binds the method parameter to the value of an HTTP matrix parameter.
·         @HeaderParam binds the method parameter to an HTTP header value.
·         @CookieParam binds the method parameter to a cookie value.
·         @FormParam binds the method parameter to a form value.
·         @DefaultValue specifies a default value for the above bindings when the key is not found.
·         @Context returns the entire context of the object (for example @Context HttpServletRequest request).


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

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.





















No comments:

Post a Comment