Reputation: 11553
I am currently working on an API that tries to do a little bit of HATEOAS by including links to related resources in API responses.
In some places, I have (ab?)used the links for things like article images. So, for example a article resource might look like this:
{
"type": "article",
"id": "1",
"links": {
"self": "/api/articles/1",
"image": "/files/b4d7802c-9cbb-4b65-9181-28cb547d2796"
},
"attributes": {
"title": "My first blog entry",
"slug": "first",
"created_at": "2016-08-01T00:00:00Z"
}
}
As you can see, I've added the link to the article's image to the links
hash. The thinking was: It's an URL, so it should probably go there. However, one could just as well argue that the article image is an attribute of the article.
So, my question: Are there any agreed-upon guidelines in the REST community that deal with how to judge whether a URL is a hypermedia link or an attribute? What are the benefits / disadvantages of either approach?
Upvotes: 0
Views: 727
Reputation: 57257
Are there any agreed-upon guidelines in the REST community that deal with how to judge whether a URL is a hypermedia link or an attribute?
A URL is a hypermedia link if it appears in a link element as defined by the media type of the representation.
When in doubt, look at your reference implementation: the world wide web. When is a URL in an HTML file a link? A elements, area elements, link elements; it's all in the spec. A sequence of characters that match the production rule for a well formed URL in the middle of a p element? Not a link.
Here's what Fielding had to say in 2008
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.
In other words, you are supposed to be using a hypermedia format where the difference between links and attributes is well specified.
Now, presuming that you have a representation where that distinction is well specified, which should you use? The answer is that you should use them in whatever combination is appropriate for your use case.
Creating a link is going to make sense for any representation that is expected to advertise a relation to some other identifiable resource. That is, as you might guess, a pretty common case on the web, and in general when using HATEOAS.
The use cases where I think URL as state makes sense are primarily going to be cases where you are editing something - if I'm going to load a representation of my profile so that I can change my homepage, then that representation is likely to include my previous homepage as state?
Of course, one might equally argue that it belongs in the update profile link relation -- again, one should check their assumptions against the "how would you do it in a web page?" heuristic.
Upvotes: 1