JSON-LD与Hydra:扩展超媒体API的语义能力
背景简介
在构建和理解超媒体API时,如何描述API提供的数据及其行为是一个核心问题。JSON-LD作为一种轻量级的链接数据格式,以及Hydra,一个扩展JSON-LD以提供额外协议语义的框架,都是为了增强API描述能力而产生的技术。
JSON-LD的局限性
JSON-LD虽然能够详细描述应用程序的语义,但其协议语义有限。它仅支持GET请求,使得客户端无法通过JSON-LD改变数据。一个典型的JSON-LD客户端在获取数据后,无法进行进一步的交互操作。
{
"@context": "http://purl.org/hydra/core/context.jsonld",
"@type": "ApiDocumentation",
"title": "Microblogging API",
"description": "You type it, we post it.",
"entrypoint": "http://example.com/api/",
"supportedClasses": [
// ...
]
}
Hydra的扩展能力
Hydra扩展了JSON-LD,为API提供了更丰富的协议语义。通过Hydra,JSON-LD可以指定各种HTTP请求,例如POST请求用于创建资源。Hydra使得API能够描述不安全的状态转换,从而为客户端提供更多交互的可能性。
```json { "@id": "#Blog", "@type": "Class", "subClassOf": "Collection", "title": "Blog", "description": "A collection of posts.", "supportedOperations": [ { "@type": "CreateResourceOperation", "method": "POST", "expects": "#BlogPost