如果您想完全接受RESTful服务设计原则,您一定希望在您的表示格式中使用超链接。 JSON有一些现有的规格,如果你不想拿出自己的:HAL和JSON API。一个天真的超媒体格式可能是这样的:
{
"playlist_id" : "666",
"created_at" : "2014-11-07 19:21:64",
"likes" : 5,
"tracks" : [
{"index" : 1,
"begin_at" : "00:02:00",
"end_at" : "00:05:23",
"_links" : {"track" : {
"href" : "/tracks/123",
"type" : "track"}}},
{"index" : 2,
"_links" : {"track" : {
"href" : "/tracks/432",
"type" : "track"}}},
{"index" : 3,
"_links" : {"track" : {
"href" : "/tracks/324",
"type" : "track"}}},
{"index" : 4,
"_links" : {"track" : {
"href" : "/tracks/567",
"type" : "track"}}}]
}
更复杂的功能都包含在这两个HAL和JSON API,就像定义嵌入的资源和链接样板。使用这样的语义,你可能会像下面这样结束:
{
"id" : "666",
"created_at" : "2014-11-07 19:21:64",
"likes" : 5,
"tracks" : [
{"id" : "123",
"index" : 1,
"begin_at" : "00:02:00",
"end_at" : "00:05:23"},
{"id" : "432",
"index" : 2},
{"id" : "324",
"index" : 3},
{"id" : "567",
"index" : 4}
],
"_links" : {
"_self" : {
"href" : "/playlists/666",
"type" : "playlist"},
"tracks" : {
"href" : "/tracks/{id}",
"type" : "track"}
},
"_embedded" : {
"track" : [
{"id" : "123",
"title" : "harder better faster stronger",
"artist" : "daft punk",
"created_at" : "2012-10-03 09:57:04",
"likes" : 234252,
"play_count" : 1203200035},
{"id" : "432",
"title" : "aerodynamic",
"artist" : "daft punk",
"created_at" : "2009-03-07 11:11:11",
"likes" : 33056,
"play_count" : 8796539}
]
}
}
另外,不要忘了使用超链接来表示实体之间的静态关系是旅程才刚刚开始。使用Hypermedia As The Engine Of Application State是真正的涅ana ......但是那时你可能会瞄准太高。
今天我一直在阅读关于大厅的更多信息。但在你的例子中,我没有看到我提到的三个上下文是如何适合的。我在哪里可以看到播放列表中的曲目数量?或者当轨道被添加? – Boedy 2014-12-03 10:41:48
您提到的“上下文”在那里。在“轨道”下的列表中,每个对象都有一个“索引”,第一个有'begin_at'和'end_at'。这些键在'track'资源本身的外部,这是一个单独的,并且使用'link'定义中的URL模板来引用。 – 2014-12-05 11:33:57