Tutorial 06

SERVER-SIDE DEVELOPMENT 2 REST

Message oriented communication and Resource oriented communication

Message oriented communication

Message oriented communication is a way of communicating between processes. Messages, which correspond to events, are the basic units of data delivered.In synchronous communication, the sender blocks waiting for the receiver to engage in the exchange.

Resource oriented communication

RoCL, the Resource oriented Communication Library we present in this paper, usesexisting low-level communication libraries to interface networking hardware. As a newintermediate-level communication library it offers a novel approach to system programmers to facilitate the development of a higher-level programming environment that supports the resource oriented computation paradigm of CoR.

Resource based nature of the REST style

The fundamental concept in any RESTful API is 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 similar to an object instance in an object-oriented programming language, 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 is homogeneous so that it 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. In the latter case, we refer to these collections as sub-collections. Sub-collections are usually used to express some kind of “contained in” relationship. We go into more detail on this in Relationships.

The diagram below illustrates the key concepts in a RESTful API…

We call information that describes available resources types, their behavior, and their relationships the resource model of an API. The resource model can be viewed as the RESTful mapping of the application data model.

Meaning of “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.

Constraints of REST, (indicating their use in the domain of web)

  • Client-server 

The REST is for explicitly for networked distributed systems, which are based on the client-server style

  • Layered System 

A client doesn’t need to know 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.

  •  Stateless 

One client can send multiple requests to the server •each request is independent •every request must contain all the necessary information so that the server can understand it and process it accordingly. •the server must not hold any information about the client state. •Any state information must stay on client –such as sessions.

  • Cacheable 

As many clients access the same server, often they may request the same resources •it is necessary that these responses might be cached, avoiding unnecessary processing, which may affect performance

  • Code-On-Demand (Optional) 

This 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.

  • Uniform Interface 

As the constraint name itself applies, you MUST decide APIs interface for resources inside the system which are exposed to API consumers and follow religiously. A resource in the system should have only one logical URI and that should provide a way to fetch related or additional data. It’s always better to synonymise a resource with a web page.Any single resource should not be too large and contain each and everything in its representation. Whenever relevant, a resource should contain links (HATEOAS) pointing to relative URIs to fetch related information.

Also, the resource representations across system should follow certain guidelines such as naming conventions, link formats or data format (xml or/and json).

All resources should be accessible through a common approach such as HTTP GET and similarly modified using a consistent approach.

Once a developer becomes familiar with one of your API, he should be able to follow the similar approach for other APIs.

Examples of different types of implementations for the elements of REST style

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

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

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

Proxy

CERN Proxy, Netscape Proxy, Gauntlet

How to define the API of RESTful web services using 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

RESTful API — also referred to as a RESTful web service — is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.

RESTFUL KEY ELEMENTS

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.

REST is a way to access resources which lie in a particular environment. For example, you could have a server that could be hosting important documents or pictures or videos. All of these are an example of resources. If a client, say a web browser needs any of these resources, it has to send a request to the server to access these resources. Now REST defines a way on how these resources can be accessed.

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.

RESTFUL METHODS

The below diagram shows mostly all the verbs (POST, GET, PUT, and DELETE) and an example of what they would mean.

Let’s assume that we have a RESTful web service is defined at the location. http://demo.guru99.com/employee . When the client makes any request to this web service, it can specify any of the normal HTTP verbs of GET, POST, DELETE and PUT. Below is what would happen If the respective verbs were sent by the client.

  1. POST – This would be used to create a new employee using the RESTful web service
  2. GET – This would be used to get a list of all employee using the RESTful web service
  3. PUT – This would be used to update all employee using the RESTful web service
  4. DELETE – This would be used to delete all employee using the RESTful web service

RESTFUL ARCHITECTURE

An application or architecture considered RESTful or REST-style has the following characteristics

  1. State and functionality are divided into distributed resources – This means that every resource should be accessible via the normal HTTP commands of GET, POST, PUT, or DELETE. So if someone wanted to get a file from a server, they should be able to issue the GET request and get the file. If they want to put a file on the server, they should be able to either issue the POST or PUT request. And finally, if they wanted to delete a file from the server, they an issue the DELETE request.
  2. The architecture is client/server, stateless, layered, and supports caching –
  • Client-server is the typical architecture where the server can be the web server hosting the application, and the client can be as simple as the web browser.
  • Stateless means that the state of the application is not maintained in REST.For example, if you delete a resource from a server using the DELETE command, you cannot expect that delete information to be passed to the next request.In order to ensure that the resource is deleted, you would need to issue the GET request. The GET request would be used to first get all the resources on the server. After which one would need to see if the resource was actually deleted.

(REF-HTTPS://WWW.GURU99.COM/RESTFUL-WEB-SERVICES.HTML)

Pros and cons of using MVC for RESTful web service development

Here are some of the features that Web API provides:

  • Strong Support for URL Routing to produce clean URLs using familiar MVC style routing semantics
  • Content Negotiation based on Accept headers for request and response serialization
  • Support for a host of supported output formats including JSON, XML, ATOM
  • Strong default support for REST semantics but they are optional
  • Easily extensible Formatter support to add new input/output types
  • Deep support for more advanced HTTP features via HttpResponseMessage and HttpRequestMessage
    classes and strongly typed Enums to describe many HTTP operations
  • Convention based design that drives you into doing the right thing for HTTP Services
  • Very extensible, based on MVC like extensibility model of Formatters and Filters
  • Self-hostable in non-Web applications 
  • Testable using testing concepts similar to MVC

Some Issues about Web API

Web API is similar to MVC but not the Same

Although Web API looks a lot like MVC it’s not the same and some common functionality of MVC behaves differently in Web API. For example, the way single POST variables are handled is different than MVC and doesn’t lend itself particularly well to some AJAX scenarios with POST data.

Code Duplication

If you build an MVC application that also exposes a Web API it’s quite likely that you end up duplicating a bunch of code and – potentially – infrastructure. You may have to create authentication logic both for an HTML application and for the Web API which might need something different altogether. More often than not though the same logic is used, and there’s no easy way to share. If you implement an MVC ActionFilter and you want that same functionality in your Web API you’ll end up creating the filter twice.

JAX-RS API and its implementations

There are two implementations

  • Jersey
  • RESTeasy

 Annotations in JAX-RS, explaining their use.

  • @Path – The @Pathannotation’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:/helloworld/{username}. 
  • @GET – The @GETannotation 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 @POSTannotation 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 @PUTannotation 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 @DELETEannotation 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.

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

Introduction to @Consumes and @Produces

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.

Resource Method Selection

So, the question is: how does the resource class know the payload’s media type and how does it select the right method to deal with it? Well, 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.

CONSUME AND PRODUCE JSON

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.

Leave a comment