Server-side development 2 - REST
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.
In
software engineering, a resource-oriented architecture is a style of software
architecture and programming paradigm for supportive designing and developing
software in the form of Internetworking of resources with "RESTful"
interfaces.
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.
Resource
Data
Resources have data associated with
them. The richness of data that can be associated with a resource is part of
the resource model for an API. It defines for example the available data
types and their behavior.
Based on my experience, I have
developed a strong conviction that the JSON data model has just the right
“richness” so that it is an ideal data model for RESTful resources. I would
recommend that everybody use it.
In JSON, just three types of data
exist:
- scalar (number, string, boolean, null).
- array
- object
Scalar types have just a single
value. Arrays contain an ordered list of values of arbitrary type. Objects
consist of a unordered set of key:value pairs (also called attributes, not to
be confused with XML attributes), where the key is a string and the value can
have an arbitrary type. For more detailed information on JSON, see the JSON web site.
Why the strong preference for JSON?
In my view, JSON has the right balance between expressiveness, and broad
availability. The three types of data (scalars, arrays and objects) are
powerful enough to describe in a natural way virtually all the data that you
might want to expose as resource, and at the same time these types are minimal
enough so that almost any modern language has built-in support for them.
XML would be the other obvious
contender. Actually, in the final incarnation of the RHEV-M API, XML is used to
describe resources, via an XMLSchema definition. With hindsight, I believe that
the XML data model is a bad choice for a RESTful API. On one side, it is too
rich, and on the other side, it lacks features. XML, as an SGML off-shoot, is
in my view great for representing structured documents, but not for
representing structured data.
Features of XML that are too rich
include:
- Attributes vs elements. An XML element can have both attributes as well as sub-elements. A data item associated with a resource could be encoded in either one, and it would not be clear beforehand which one a client or a server should use.
- Relevance of order. The order between child-elements is relevant in XML. It is not natural in my view for object attributes to have ordering.
The limitations of the XML data
model are:
- Lack of types. Elements in XML documents do not have types, and in order to use types, one would have to use e.g. XMLSchema. XMLSchema unfortunately is a strong contender for the most convoluted specification ever written.
- Lack of lists. XML cannot natively express lists. This can lead to issues whereby it is not clear whether a certain element is supposed to be a list or an object, and where that element ends up being both.
Application
Data
We define the data that can be
associated with a resource in terms of the JSON data model, using the following
mapping rules:
- Resources are modeled as a JSON object. The type of the resource is stored under the special key:value pair “_type”.
- Data associated with a resource is modeled as key:value pairs on the JSON object. To prevent naming conflicts with internal key:value pairs, keys must not start with “_”.
- The values of key:value pairs use any of the native JSON data types of string, number, boolean, null, or arrays thereof. Values can also be objects, in which case they are modeling nested resources.
- Collections are modeled as an array of objects.
We will also refer to key:value
pairs as attributes of the JSON object, and we will be sloppy and use that same
term for data items associated with resources, too. This use of attributes is
not to be confused with XML attributes.
REST
Metadata
In addition to exposing application
data, resources also include other information that is specific to the RESTful
API. Such information includes URLs and relationships.
The following table lists generic
attributes that are defined and have a specific meaning on all resources. They
should not be used for mapping application model attributes.
Representational
State Transfer (REST) is a software architectural style that
defines a set of constraints to be used for creating Web services. ... In a RESTful
Web service, requests made to a resource's URI will elicit a response with a
payload formatted in HTML, XML, JSON, or some other format.
Representational
State Transfer (REST) is a software architectural
style that defines a set of constraints to be used for creating Web services. Web services that
conform to the REST architectural style, termed RESTful ... Other kinds
of Web
services, such as SOAP Web services, expose their own arbitrary
sets of operations.
Representational
State Transfer (REST) is a software architectural style that defines a set of
constraints to be used for creating Web services. Web services that conform to
the REST architectural style, termed RESTful Web services (RWS), provide
interoperability between computer systems on the Internet. RESTful Web services
allow the requesting systems to access and manipulate textual representations
of Web resources by using a uniform and predefined set of stateless operations.
Other kinds of Web services, such as SOAP Web services, expose their own arbitrary
sets of operations. "Web resources" were first defined on the World
Wide Web as documents or files identified by their URLs. However, today they
have a much more generic and abstract definition that encompasses everything or
entity that can be identified, named, addressed, or handled, in any way
whatsoever, on the Web. In a RESTful Web service, requests made to a resource's
URI will elicit a response with a payload formatted in HTML, XML, JSON, or some
other format. The response can confirm that some alteration has been made to
the stored resource, and the response can provide hypertext links to other
related resources or collections of resources. When HTTP is used, as is most
common, the operations (HTTP methods) available are GET, HEAD, POST, PUT,
PATCH, DELETE, CONNECT, OPTIONS and TRACE.By using a stateless protocol and
standard operations, RESTful systems aim for fast performance, reliability, and
the ability to grow, by re-using components that can be managed and updated
without affecting the system as a whole, even while it is running.
RESTful
web services are built to work best on the Web. Representational State Transfer
(REST) is an architectural style that specifies constraints, such as the
uniform interface, that if applied to a web service induce desirable
properties, such as performance, scalability, and modifiability that enable
services to work best on the Web. In the REST architectural style, data and
functionality are considered resources and are accessed using Uniform Resource
Identifiers (URIs), typically links on the Web. The resources are acted upon by
using a set of simple, well-defined operations. The REST architectural style
constrains an architecture to a client/server architecture and is designed to
use a stateless communication protocol, typically HTTP. In the REST
architecture style, clients and servers exchange representations of resources
by using a standardized interface and protocol.The following principles
encourage RESTful applications to be simple, lightweight, and fast:Resource
identification through URI: A RESTful web service exposes a set of resources
that identify the targets of the interaction with its clients. Resources are
identified by URIs, which provide a global addressing space for resource and
service discovery. See The @Path Annotation and URI Path Templates for more
information.Uniform interface: Resources are manipulated using a fixed set of
four create, read, update, delete operations: PUT, GET, POST, and DELETE. PUT
creates a new resource, which can be then deleted by using DELETE. GET retrieves
the current state of a resource in some representation. POST transfers a new
state onto a resource. See Responding to HTTP Methods and Requests for more
information.Self-descriptive messages: Resources are decoupled from their
representation so that their content can be accessed in a variety of formats,
such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the
resource is available and used, for example, to control caching, detect
transmission errors, negotiate the appropriate representation format, and
perform authentication or access control. See Responding to HTTP Methods and
Requests and Using Entity Providers to Map HTTP Response and Request Entity
Bodies for more information.Stateful interactions through hyperlinks: Every interaction
with a resource is stateless; that is, request messages are self-contained.
Stateful interactions are based on the concept of explicit state transfer.
Several techniques exist to exchange state, such as URI rewriting, cookies, and
hidden form fields. State can be embedded in response messages to point to
valid future states of the interaction. See Using Entity Providers to Map HTTP
Response and Request Entity Bodies and “Building URIs” in the JAX-RS Overview
document for more information.
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.
JAX-RS Media Types
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.
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.


Comments
Post a Comment