Restful API with HATEOAS
Introduction
HATEOAS is an acronym that stands for Hypermedia as the Engine of Application State and it is a constraint of REST architecture that aligns with the third level of maturity according to the Richardson Maturity model.
In addition to using HTTP verbs to define actions and the uri path to denote resource structure in a traditional REST API, HATEOAS adds hypermedia links to the response so that a client can navigate standardized entity and collection recursively from a base of an application.
Example
If we have a Product api with an Accessory subresources, we expect an API with the following design:
- Product: GET|POST|PUT|PATCH|DELETE
products/:productId?
- Accessory: GET|POST|PUT|PATCH|DELETE
products/:productId/accessories/:accessoryId?
Furthermore, we expect that we will either get a collection or an entity depending if we specify a resource to get:
Collection:
Request
GET http://localhost:8080/products
Response
{"_links": {"self": {"href": "http://localhost:8080/products"}},"_embedded": {"products": [{"_links": {"self": {"href": "http://localhost:8080/products/588722"}},"id": "588722","width": "60","height": "20","price": "8.99"},{"_links": {"self": {"href": "http://localhost:8080/products/636856"}},"id": "636856","width": "40","height": "30","price": "4.99"}]}}
Entity
Request
GET http://localhost:8080/products/636856
Response
{"_links": {"self": {"href": "http://localhost:8080/products/636856"}},"id": "636856","width": "40","height": "30","price": "4.99"}