Adding Flexibility to your REST Implementation with Yoga
如何使用REST提供一个基于领域模型图的简单REST API?有两个选择,IBM, SAP, Microsoft, Red Hat提倡的OData,还有一个轻量实现方案Yoga.
对于如下的领域模型图:
如果用传统REST方式想得到图中从User-->Friends-->Favortie--?Albums-->Songs这样一个图路径,可能使用多次调用,如:
GET /user/1.json (Get user) GET /user/2.json (Get detailed friend entities) GET /user/3.json ... GET /artist/1.json (Get favorite artists) GET /artist/2.json ... GET /album/1.json (Get albums for artists) GET /album/2.json ... GET /song/1.json (Get songs for albums) GET /song/2.json |
而是要Yoga提供的selector语法,可以通过如下URL:
GET /user/1.json?selector=friends(favoriteArtists(albums(songs))) |
例如: GET /user/1.json?selector=id,name,favoriteArtists(id,name) 得到的JSON内容如下:
{ "id": 1, "name": "Carter Page", "favoriteArtists": [ { "id": 1, "name": "Arcade Fire" }, { "id": 3, "name": "Neutral Milk Hotel" } ] } |
Yoga还直接提供对领域模型的元注释:
@Core public long getId() { return _id; } @Core public String getName() { return _name; } |
这样得到的Json结果和上面是一样的。
Yoga支持 Spring MVC REST, Jersey, or RESTEasy。