Search code examples
apihateoas

HATEOAS - Load resource when refresh the page


I'm starting with HATEOAS and I have a simple question. When I want load a specific resource by its ID, how is the best way to do this? Currently I do a request to /root route, this route gives me one link like this:

{ "rel": "order", "href": "http://api.com/orders/:id" }

Using template string is a nice way?

Other question is: And when I have 10 resource types, will I need put this 10 times in root response?


Solution

  • Counterquestion - where did you get your ids from?

    I assume from crawling through your API, following links - but why don't you just save the whole link that is returned by the server, rather than just the id?

    That is actually the idea of HATEOAS: that your API is explorable, and you rather just use the links that are returned by the API, rather than assembling your own from ids you extracted from resources.

    The advantage is that when the API changes (paths get renamed etc.), you don't need to change your client code.

    But that is probably not a good strategy if you need to keep the links for a longer time (e.g. when you want to bookmark them in some form).

    Then it's a good idea to use link templates, as you suggested, and retrieve the template for the links from the root resource (or from suitable sub-resources that are easily accessible from the root resource).

    Like this you can be sure you always have valid links, but yes, it also means you have to put them all in there (or at least the ones you support for deep linking).

    For expressing templated links, you can use HAL: stateless.co/hal_specification.html