Sobes.tech
Middle+

Tell me about the HATEOAS principle.

sobes.tech AI

Answer from AI

HATEOAS (Hypermedia as the Engine of Application State) is a constraint of the REST architecture that prescribes that the client interacts with the REST service entirely through hypermedia provided by the server in responses.

Instead of knowing the URIs of all resources and actions in advance, the client receives this information in the form of links and forms embedded in resource representations.

Key aspects:

  • Self-descriptive messages: Each message sent to the client, in addition to data, contains links to related resources and available actions.
  • No need to know URIs in advance: The client follows hypermedia to navigate the API and perform actions. It only knows the initial access point.
  • Enhanced evolvability: The server can change resource URIs without changing the client logic, as long as it continues to provide the appropriate hypermedia.
  • Reduced client-server coupling: The client depends less on the internal structure of the server.

Example of a resource representation with HATEOAS:

{
  "orderId": "123",
  "status": "Pending",
  "items": [
    {
      "itemId": "A45",
      "quantity": 2
    }
  ],
  "_links": {
    "self": {
      "href": "/orders/123"
    },
    "cancel": {
      "href": "/orders/123/cancel",
      "method": "POST" // Indicates the type of action
    },
    "customer": {
      "href": "/customers/C99"
    }
  }
}

Here, _links contains URIs for the resource itself, the ability to cancel the order, and the related customer. The client, upon receiving this representation, knows how to perform these actions without having their URIs hardcoded in its code.

Although HATEOAS is a key principle of REST, its full and consistent application can be challenging in practice.