H.A.T.E.O.A.S example
Suppose you have an e-commerce website with the following resources:
GET /products- Returns a list of products.GET /products/{id}- Returns a specific product by ID.POST /orders- Creates a new order.GET /orders- Returns a list of all orders.GET /orders/{id}- Returns a specific order by ID.
To implement HATEOAS in this API, each response should include links to related resources that the client can navigate to. For example:
-
GET /products- Returns a list of products, each with a link to the product's details:{ "products": [ { "id": 1, "name": "Product 1", "description": "Product 1 description", "price": 9.99, "_links": { "self": { "href": "/products/1" } } }, { "id": 2, "name": "Product 2", "description": "Product 2 description", "price": 19.99, "_links": { "self": { "href": "/products/2" } } } ], "_links": { "self": { "href": "/products" } } } -
GET /products/{id}- Returns a specific product by ID, with links to related resources:{ "id": 1, "name": "Product 1", "description": "Product 1 description", "price": 9.99, "_links": { "self": { "href": "/products/1" }, "order": { "href": "/orders", "method": "POST", "title": "Order Product 1" } } }In this example, the product details include a link to create a new order for this product, via a
POST /ordersrequest. -
POST /orders- Creates a new order, with a link to the newly-created order:{ "id": 123, "product_id": 1, "quantity": 1, "_links": { "self": { "href": "/orders/123" }, "product": { "href": "/products/1" } } } -
GET /orders- Returns a list of all orders, each with a link to the order's details:{ "orders": [ { "id": 123, "product_id": 1, "quantity": 1, "_links": { "self": { "href": "/orders/123" } } }, { "id": 124, "product_id": 2, "quantity": 2, "_links": { "self": { "href": "/orders/124" } } } ], "_links": { "self": { "href": "/orders" } } } -
GET /orders/{id}- Returns a specific order by ID, with links to related resources:{ "id": 12345, "customer": { "id": 54321, "name": "John Smith" }, "items": [ { "id": 1, "name": "Product A", "price": 9.99, "quantity": 2, "links": [ { "rel": "self", "href": "/products/1" } ] }, { "id": 2, "name": "Product B", "price": 14.99, "quantity": 1, "links": [ { "rel": "self", "href": "/products/2" } ] } ], "total": 34.97, "status": "delivered", "links": [ { "rel": "self", "href": "/orders/12345" }, { "rel": "customer", "href": "/customers/54321" } ] }