How to present collections in HAL (JSON version) when performing REST

Say I have a collection of books, which we will call a library. GET domain.com/library should return a list of books in the library in HAL-compatible JSON. How do I format JSON? How could I embed book resources? Here is the format I'm thinking of now:

{ "books": [ { "name": "Fight Club", "_links": { "self": { "href": "domain.com/library/Fight-Club" }, }, ... }, .... ], "_links" : { "search": { "href": "domain.com/library/search" }, ... }, "_embedded" : { "Fight Club": { "author": "Chuck Palahniuk", ... [Same links as above] } } } 
+5
source share
1 answer

As stated in the HAL specification, the _embedded object _embedded intended for sub-resources of this resource. So, your bare bones of HAL JSON will look like this.

 { "_links": { "self": { "href": "/library" } }, "_embedded": { "item": [{ "_links": { "self": { "href": "/library/Fight-Club" } }, "author": "Chuck Palahniuk", "title": "Fight Club" }] } } 

The immediate properties of the _embedded object are link relationships . The item relation is a standard relation, which means that the resource is an element belonging to the context resource (in this case, your library). You can create your own link relationship using CURIEs .

Note the absence of the books array in the top-level object. You can turn it on if you want, but it's just a convenience. The HAL library will only know what you put in _links and _embedded . See this discussion regarding collections in the HAL and the human factor when deciding where to place your data.

+11
source

Source: https://habr.com/ru/post/1200056/


All Articles