tute 6

Introduction to REST

Message Oriented Communication
  • Messages are sent through a channel abstraction
  • The channel connects two running processes
  • Time coupling between sender and receiver
  • Transmission time is measured in terms of milliseconds, typically
Resource Oriented Communication
  • Main focus is about Request addressing.
  • Unique address per resource.
  • Application interface is generic to the request mechanism.
  • Nothing directly linked to address/ URL.
REST
Representational State Transfer (REST) is a style of architecture based on a set of principles that describe how networked resources are defined and addressed. These principles were first described in 2000 by Roy Fielding as part of his doctoral dissertation. REST is an alternative to SOAP and JavaScript Object Notation (JSON).
It is important to note that REST is a style of software architecture as opposed to a set of standards. As a result, such applications or architectures are sometimes referred to as RESTful or REST-style applications or architectures. REST has proved to be a popular choice for implementing Web Services. For example, the books suggested at the bottom of many of these article pages are dynamically generated, in part, using a REST architecture. It is one of the options for Amazon Web Services
An application or architecture considered RESTful or REST-style is characterized by:
  • State and functionality are divided into distributed resources
  • Every resource is uniquely addressable using a uniform and minimal set of commands (typically using HTTP commands of GET, POST, PUT, or DELETE over the Internet)
  • The protocol is client/server, stateless, layered, and supports caching
Representations in REST style
REST components perform actions on a resource by using a representation to capture the current or intended state of that resource and transferring that representation between components. A representation is a sequence of bytes, plus representation metadata to describe those bytes. Other commonly used but less precise names for a representation include: document, file, and HTTP message entity, instance, or variant.
A representation consists of data, metadata describing the data, and, on occasion, metadata to describe the metadata (usually for the purpose of verifying message integrity). Metadata is in the form of name-value pairs, where the name corresponds to a standard that defines the value’s structure and semantics. Response messages may include both representation metadata and resource metadata: information about the resource that is not specific to the supplied representation.
Control data defines the purpose of a message between components, such as the action being requested or the meaning of a response. It is also used to parameterize requests and override the default behavior of some connecting elements. For example, cache behavior can be modified by control data included in the request or response message.
Depending on the message control data, a given representation may indicate the current state of the requested resource, the desired state for the requested resource, or the value of some other resource, such as a representation of the input data within a client’s query form, or a representation of some error condition for a response. For example, remote authoring of a resource requires that the author send a representation to the server, thus establishing a value for that resource that can be retrieved by later requests. If the value set of a resource at a given time consists of multiple representations, content negotiation may be used to select the best representation for inclusion in a given message.
Constraints of REST
  • Client-Server
The first constraints added to our hybrid style are those of the client-server architectural style. Separation of concerns is the principle behind the client-server constraints. By separating the user interface concerns from the data storage concerns, we improve the portability of the user interface across multiple platforms and improve scalability by simplifying the server components. Perhaps most significant to the Web, however, is that the separation allows the components to evolve independently, thus supporting the Internet-scale requirement of multiple organizational domains.
  • Layerd System
In order to further improve behavior for Internet-scale requirements, we add layered system constraints. The layered system style allows an architecture to be composed of hierarchical layers by constraining component behavior such that each component cannot “see” beyond the immediate layer with which they are interacting. By restricting knowledge of the system to a single layer, we place a bound on the overall system complexity and promote substrate independence. Layers can be used to encapsulate legacy services and to protect new services from legacy clients, simplifying components by moving infrequently used functionality to a shared intermediary. Intermediaries can also be used to improve system scalability by enabling load balancing of services across multiple networks and processors. The primary disadvantage of layered systems is that they add overhead and latency to the processing of data, reducing user-perceived performance. For a network-based system that supports cache constraints, this can be offset by the benefits of shared caching at intermediaries. Placing shared caches at the boundaries of an organizational domain can result in significant performance benefits. Such layers also allow security policies to be enforced on data crossing the organizational boundary, as is required by firewalls.
  • Stateless
We next add a constraint to the client-server interaction: communication must be stateless in nature, such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. This constraint induces the properties of visibility, reliability, and scalability. Visibility is improved because a monitoring system does not have to look beyond a single request datum in order to determine the full nature of the request. Reliability is improved because it eases the task of recovering from partial failures. Scalability is improved because not having to store state between requests allows the server component to quickly free resources, and further simplifies implementation because the server doesn’t have to manage resource usage across requests. Like most architectural choices, the stateless constraint reflects a design trade-off. The disadvantage is that it may decrease network performance by increasing the repetitive data (per-interaction overhead) sent in a series of requests, since that data cannot be left on the server in a shared context. In addition, placing the application state on the client-side reduces the server’s control over consistent application behavior, since the application becomes dependent on the correct implementation of semantics across multiple client versions.
  • Casheable
In order to improve network efficiency, we add cache constraints to form the client-cache-stateless-server style. Cache constraints require that the data within a response to a request be implicitly or explicitly labeled as cacheable or non-cacheable. If a response is cacheable, then a client cache is given the right to reuse that response data for later, equivalent requests. The advantage of adding cache constraints is that they have the potential to partially or completely eliminate some interactions, improving efficiency, scalability, and user-perceived performance by reducing the average latency of a series of interactions. The trade-off, however, is that a cache can decrease reliability if stale data within the cache differs significantly from the data that would have been obtained had the request been sent directly to the server.
  • Code-On-Demand
The final addition to our constraint set for REST comes from the code-on-demand style. REST allows client functionality to be extended by downloading and executing code in the form of applets or scripts. This simplifies clients by reducing the number of features required to be pre-implemented. Allowing features to be downloaded after deployment improves system extensibility. However, it also reduces visibility, and thus is only an optional constraint within REST. The notion of an optional constraint may seem like an oxymoron. However, it does have a purpose in the architectural design of a system that encompasses multiple organizational boundaries. It means that the architecture only gains the benefit (and suffers the disadvantages) of the optional constraints when they are known to be in effect for some realm of the overall system. For example, if all of the client software within an organization is known to support Java applets, then services within that organization can be constructed such that they gain the benefit of enhanced functionality via downloadable Java classes. At the same time, however, the organization’s firewall may prevent the transfer of Java applets from external sources, and thus to the rest of the Web it will appear as if those clients do not support code-on-demand. An optional constraint allows us to design an architecture that supports the desired behavior in the general case, but with the understanding that it may be disabled within some contexts.
  • Uniform Interface
The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components. By applying the software engineering principle of generality to the component interface, the overall system architecture is simplified and the visibility of interactions is improved. Implementations are decoupled from the services they provide, which encourages independent evolvability. The trade-off, though, is that a uniform interface degrades efficiency, since information is transferred in a standardized form rather than one which is specific to an application’s needs. The REST interface is designed to be efficient for large-grain hypermedia data transfer, optimizing for the common case of the Web, but resulting in an interface that is not optimal for other forms of architectural interaction.

Elements of REST style


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. The table below summarizes the connector types:
Connector TypeDescriptionExample
ClientSending requests, receiving responses.HTTP library
ServerListening for requests, sending responses.Web Server API
CacheCan be located at the client or server connector to save cacheable responses, can also be shared between several clientsBrowser cache
ResolverTransforms resource identifiers into network addresses.bind (DNS lookup library)
TunnelRelays requests, any component can switch from active behavior to a tunnel behavior.SOCKS, SSL after HTTP CONNECT
  • Components
In REST, the various software that interacts with one another are called components. They are categorized by roles summarized in the table below:
Component RoleDescriptionExample
Origin ServerUses a server connector to receive the request, and is the definitive source for representations of its resources. Each server provides a generic interface to its services as a resource hierarchy.Apache httpd, Microsoft IIS
User AgentUses a client connector to initiate a request and becomes the ultimate recipient of the response.Browser like Netscape Navigator etc
GatewayAct as both, client and server in order to forward – with possible translation – requests and responses.Squid, CGI, Reverse Proxy
ProxyCERN 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. REST identifies six data elements: a resource, resource identifier, resource metadata, representation, representation metadata, and control data, shown in the table below:
Data ElementDescriptionExample
ResourceAny information that can be named is a resource. A resource is a conceptual mapping to a set of entities not the entity itself. Such a mapping can change over time. In general, a RESTful resource is anything that is addressable over the Web.Title of a movie from IMDb, A Flash movie from YouTube, Images from Flickr etc
Resource IdentifierEvery resource must have a name that uniquely identifies it. Under HTTP these are called URIs. Uniform Resource Identifier (URI) in a RESTful system is a hyperlink to a resource. It is the only means for clients and servers to exchange representations of resources.The relationship between URIs and resources is many to one. A resource can have multiple URIs which provide different information about the location of a resource.Standardized format of URI:scheme://host:port/path?queryString#fragmente.g:http://some.domain.com/orderinfo?id=123
Resource metadataThis describes the resource. A metadata provides additional information such as location information, alternate resource identifiers for different formats or entity tag information about the resource itself.Source link, vary
RepresentationIt is something that is sent back and forth between clients and servers. So, we never send or receive resources, only their representations. A representation captures the current or intended state of a resource. A particular resource may have multiple representationsSequence of bytes, HTML document, archive document, image document
Representation metadataThis describes the representation.Headers (media-type)
Control dataThis defines the purpose of a message between components, such as the action being requested.If-Modified-Since, If-Match

RESTful URLs

REST is used to build Web services that are lightweight, maintainable, and scalable in nature. A service which is built on the REST architecture is called a RESTful service. The underlying protocol for REST is HTTP, which is the basic web protocol. REST stands for Representational State Transfer 
The key elements of a RESTful implementation are as follows:
  1. Resources – The first key element is the resource itself. Let assume that a web application on a server has records of several employees. Let’s assume the URL of the web application is http://demo.guru99.com. Now in order to access an employee record resource via REST, one can issue the command http://demo.guru99.com/employee/1 – This command tells the web server to please provide the details of the employee whose employee number is 1.
  2. Request Verbs – These describe what you want to do with the resource. A browser issues a GET verb to instruct the endpoint it wants to get data. However, there are many other verbs available including things like POST, PUT, and DELETE. So in the case of the example http://demo.guru99.com/employee/1 , the web browser is actually issuing a GET Verb because it wants to get the details of the employee record.
  3. Request Headers – These are additional instructions sent with the request. These might define the type of response required or the authorization details.
  4. Request Body – Data is sent with the request. Data is normally sent in the request when a POST request is made to the REST web service. In a POST call, the client actually tells the web service that it wants to add a resource to the server. Hence, the request body would have the details of the resource which is required to be added to the server.
  5. Response Body – This is the main body of the response. So in our example, if we were to query the web server via the request http://demo.guru99.com/employee/1 , the web server might return an XML document with all the details of the employee in the Response Body.
  6. Response Status codes – These codes are the general codes which are returned along with the response from the web server. An example is the code 200 which is normally returned if there is no error when returning a response to the client.

Use MVC with REST & RESTful web services

Reasons to Use Spring for Creating RESTful Web Services in Java
1. 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.
2. 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.
3. 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. This means you don’t need to annotate each method with the @ResponseBody annotation. This also makes your code much cleaner.
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. If you remember, we use @RequestParam to get the value of those query parameters but, not to worry, Spring MVC also provides a @PathVariable annotation which can extract data from a URL. It allows the controller to handle requests for parameterized URLs.
5. 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. For example, ContentNegotiatingViewResolver can look at the file extension of requests or Accept header to find out the correct representation of a resource for the client.

6. 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.
7. TheSpring framework also provides a template class, RestTemplate, which is similar to JdbcTemplate, and JmsTemplate, which can consume REST resources. You can use this class to test your RESTful web service or develop REST clients.
JAX-RS API
There are two main implementation of JAX-RS API.
  1. Jersey
  2. RESTEasy
Annotations in JAX-RS
Annotations in the JAX-RS API are used to provide meta-data around the web resource. A typical example is to use the @GET annotation with the @Path annotation to identify the method that should handle a GET request to the specified URI in the @Path annotation.
@Path  : The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted, for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example, you could ask for the name of a user, and pass it to the application as a variable in the URI, like this, /helloworld/{username}.
@GET  : The @GET annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@POST  : The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@PUT  : The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP PUT requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@DELETE  : The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@HEAD  : The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@PathParam  : The @PathParam annotation is a type of parameter that you can extract for use in your resource class. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
@QueryParam  : The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
@Consumes  : The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.
@Produces  : The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client, for example, “text/plain”.
@Provider  : The @Provider annotation is used for anything that is of interest to the JAX-RS runtime, such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body using a MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return a Response that wraps the entity, and which can be built using Response.ResponseBuilder.

Comments

Popular posts from this blog

tute 4

Tute 3 Answers

tute 8