Designing Restful Web Services Part 2 - HATEOAS

HATEOAS stands for ‘Hypermedia As The Engine Of Application State’.

HATEOAS is a principle in which your data formats drive the state transitions in your application.

Links to other resources are embedded within the response data format and going to these links will change the state of your applications.

The response and links returned may be different every time for the same resource based on the current state of the resource, and thus HATEOS acts as an engine that tells you what new interactions you can do next and where to go to transition the state.

 

To understand HATEOAS, you need to understand what hypertext and hypermedia is.

Hypertext and hypermedia documents contain not just data, but links to other resources.

HATEOAS is the same principle that is behind linking and form submissions over internet, as they change the state of either your browser (client) or server resources.

Hyperlinks make it possible for people and even search engines to search through the web pages one by one following the hyperlinks. When you click on a hyperlink, the state of your browser (client) will change.

An HTML form is a self-describing interaction between client to server. A form submission may create new resources at the server and thus changes the state of resources at server side.  

 

Adding links to documents using syntax from the Atom Syndication Format

In HATEOAS; you need to add links in your XML or JSON documents. We need to decide on how we would add links to our XML or JSON documents.

Many XML based REST web services use syntax from the Atom Syndication Format for implementing HATEOAS.

The Atom Syndication Format is an XML language used for web feeds and feed entries may be headlines, full-text articles, excerpts, summaries, and/or links to contents. We can reuse the syntax and attributes of the atom link feed element to implement HATEOAS in web services. Though atom feed entries are XML based, we can use the same set of attributes for JSON as well.

We may also use http headers to exchange links with your client than using the atom link syntax to embed the links into the xml.

The "atom:link" element entry of an atom feed defines a reference from an entry or feed to a Web resource.  The "atom:link" element has various attributes such as href, rel, type, hreflang, title, and length.

To implement HATEOAS similar to atom link element, we mainly use href, rel, type and hreflang attributes from the "atom:link" element.

  • The rel attribute specifies the relationship between the current document and the linked document. This may be a logical simple name used to reference the link and might have a value of “self” if it is pointing to itself.

  • The href attribute specifies the actual URL being linked.

  • The type attribute specifies the mediatype of the resource exchanged (e.g. application/xml).  The hreflang attribute is used to specify the language the data format is translated into (e.g. French, German, and English etc.).

 

XML Example

<employee>

<id>456</id>

<name>Sneha</name>

<link rel=”manager”

            href=”/ employees/id/123”

            type=”application/xml” />

</employee>

 

JSON Example

{

“id”: “456”,

“name”: “Sneha”,

“links”: [

            {

                          “rel”: “manager”,

                          “href=”: “/employees/id/123”,

  “type”: “application/xml”

            }

]

…       

}

 

Adding links to Http Headers

You can have the standard Link: header in HTTP to provide the link as well as a relationship.

Previous example link may be sent as a Link header as below:

HTTP/1.1 200 OK

Content-Type: application/xml

Link: <http://.../employees/id/123>; rel = manager

Note that the URI is enclosed by <> followed by attributes delimited by semicolons. The rel attribute is a required attribute and may also specify an optional type attribute.

One advantage of using Link header over embedding atom links in the document is that if client is only interested in the link, then it does not have to do a GET to get all data and then parse it to get the link element; instead it can do a HEAD invocation to get the header details.

However for doing data aggregation, embedding atom links in the document may be a better approach.

 

Advantages of using HSTEOAS with web services

  • Location transparency – Client has to know only about the logical link name (rel attribute) and the server may change the location and send a different location over the network without breaking the client code.

  • Decoupling interaction details – We can reduce the amount of predefined knowledge client need to have about the service by passing in those details as a link. This will avoid the need for client to do any bookkeeping of the interaction. Providing pagination details (like the current set, query parameter names for offset and limit etc.) is a very popular example. Now server has the control to guide the client through interactions by providing links.

  • Reduced state transition errors - Making a request to a server and receiving allowable operations as links will help reduce errors such as making an invalid state transition. Consider an online order processing application. You might be allowed to cancel an order until some point of the order processing. Client can first do a GET to get the document representing the order. If the document contains a cancel link, the client can then cancel the request by making a POST or PUT to the URI referenced in the link.

 

More Background and Explanations

Hypertext and Hypermedia

Hypertext is text with references (hyperlinks) to other text. The hypertext pages are interconnected by hyperlinks. Hypermedia is an extension of the term hypertext. Hypermedia is a nonlinear medium of information which includes graphics, audio, video, plain text and hyperlinks. The World Wide Web is a classic example of hypermedia as information is connected through a series of hyperlinks embedded within HTML documents. In summary, hypermedia documents contain not just data, but links to other resources.

 

Atom Syndication Format

The Atom Syndication Format is an XML language used for web feeds. Web feeds allow software programs to check for updates published on a website. To provide a web feed, the site owner may use specialized programs that publishes a list (or "feed") of recent articles or content in a standardized, machine-readable format. The feed can then be downloaded by programs that use it. A feed contains entries, which may be headlines, full-text articles, excerpts, summaries, and/or links to content on a website, along with various metadata. The "atom:link" element entry of a feed defines a reference from an entry or feed to a Web resource.  The "atom:link" element has various attributes such as href, rel, type, hreflang, title, and length.

 

We will see how to implement HATEOAS using JAX-RS soon to have a better understanding of concepts discussed here.

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)