在RESTful Web API一书中,作者建议公开一个配置文件并使用一种确认链接关系的内容类型。由JSON-LD扩展的Hydra似乎符合这些要求,我想在设计新API时使用它们。
我目前遇到了性能问题。假设我有一个在线自行车商店,我想要检索有关给定自行车车轮的信息。
根据Hydra规范,在我看来,我需要发送2个请求来获取有关车轮的详细信息。 第一个要求是自行车本身:
GET /mybike HTTP/1.1
Host: wowbike.com
响应包含一个Hydra :: Link到轮子集合:
HTTP/1.1 200 OK
Content-Type: application/ld+json
{
"@context" :
{
"Bike": "/contexts/vocab#Bike"
},
"@id" : "/mybike",
"@type" : "Bike",
"size" : "L",
"wheels" : "/mybike/wheels" // "wheels" is a "hydra:Link"
}
现在我可以向wheel资源发送第二个请求以获取详细信息:
GET /mybike/wheels HTTP/1.1
Host: wowbike.com
HTTP/1.1 200 OK
Content-Type: application/ld+json
{
"@context":
{
"Collection": "http://www.w3.org/ns/hydra/core#Collection",
"Wheel" : "/contexts/vocab#Wheel"
},
"@type" : "Collection",
"@id" : "/mybike/wheels",
"member" :
[
{
"@id" : "/mybike/wheels/firstwheel",
"@type" : "Wheel",
"color" : "blue"
},
{
"@id" : "/mybike/wheels/secondwheel",
"@type" : "Wheel",
"color" : "white"
}
]
}
发送单个请求并获得如下所示的响应是否有效?
GET /mybike HTTP/1.1
Host: wowbike.com
HTTP/1.1 200 OK
Content-Type: application/ld+json
{
"@context" :
{
"Collection": "http://www.w3.org/ns/hydra/core#Collection",
"Bike" : "/contexts/vocab#Bike",
"Wheel" : "/contexts/vocab#Wheel"
},
"@id" : "/mybike",
"@type" : "Bike",
"size" : "L",
"wheels" :
{
"@id" : "/mybike/wheels",
"@type" : "Link",
"member":
[
{
"@id" : "/mybike/wheels/firstwheel",
"@type" : "Wheel",
"color" : "blue"
},
{
"@id" : "/mybike/wheels/secondwheel",
"@type" : "Wheel",
"color" : "white"
}
]
}
}
答案 0 :(得分:6)
很高兴看到您考虑使用JSON-LD和Hydra。当然,可以在一个响应中获取所有数据。但是,您不必将集合的类型从Collection
更改为Link
。此外,您可能想稍微调整一下您的上下文。总而言之,您的回答看起来有点像这样:
{
"@context": [
"http://www.w3.org/ns/hydra/context.jsonld",
{ "@vocab": "/contexts/vocab#" }
],
"@id": "/mybike",
"@type": "Bike",
"size": "L",
"wheels": {
"@id" : "/mybike/wheels",
"@type" : "Collection",
"member": [
{
"@id" : "/mybike/wheels/firstwheel",
"@type" : "Wheel",
"color" : "blue"
},
{
"@id" : "/mybike/wheels/secondwheel",
"@type" : "Wheel",
"color" : "white"
}
]
}
}
我在这里导入Hydra的上下文,然后覆盖默认词汇表,这意味着Hydra上下文中尚未定义的所有内容都通过将其附加到/contexts/vocab#
来扩展。因此,Bike
例如将扩展为/contexts/vocab#Bike
。
顺便说一下。如果你使用它,你应该加入W3C Community Groupw working on Hydra。我们还有mailing list,您的所有问题都将得到解答。
找到加入论坛的说明