by Răzvan Ștețcu
I’m currently a .NET Junior Software Developer at Wayfare, but I also worked with Progress OpenEdge for one year before. As I really wanted to engage myself in .NET technology so I started learning for a few months.
Today I want to share a simple implementation of HATEOAS, the one that I chose for my Internal Project.
"A hypermedia-driven site provides information to navigate the site's REST interfaces dynamically by including hypermedia links with the responses." Spring.io
I know, It might sound confusing, I was confused too when I first read this sentence.
HATEOAS is all about helping developers and other API users to communicate with the service, without having to read some document or other specification. This opens up the ability to browse around data a lot easier and helps client developers to build a mental model of the API.
Let’s say that this code represents an Employee object:
The JSON representation for this object usually looks like this:
You didn’t get enough details from this JSON, it doesn’t tell you what you can do with this data. If for example, you want to delete this employee, you will have to search the URL to delete it in the documentation or even in the code.
Href contains the complete target URL for that source.
Rel contains the link relationship type.
Method contains the HTTP method that you will have to use for the request.
First, we need a LinkDto class, the structure of a link.
Second, we create a base class for our linked resources.
Model classes should inherit LinkedResourceBaseDto. This contains links, a list of LinkDto.
Now, the method that creates a link to get the actual Employee will look like:
This method takes an Employee object, adds the links to it and return the object back. UrlHelper _urlHelper – takes the controller route name and the parameters and generates the URL. Instead of returning a simple Employee from the controller, we will return CreateLinksForEmployee(employee).
As we can see, with this in place, we will get links only for each separate book, not for the book resource itself. We need a wrapper class to modify the JSON to contain the links for the book resource, together with the links for every book.
Now, we can use this class to create a new method, that will generate links for the book resource itself.
The same as above, instead of returning a list of Employees, we will return: