链接和嵌入
最后更新于:2021-11-29 11:10:28
Linking and Embedding
The GC REST API incorporates hyperlinking throughout the API to allow discoverability and browsability, as well as GC REST API在整个API中集成了超链接,以允许可发现性和可浏览性,并将相关资源嵌入到一个响应中。虽然REST API不完全符合整个HAL标准,但它实现了该标准的._links
和._embedded
,如下所述。
链接
The _links
property of the response object contains a map of links to other API resources, grouped by “relation.” The relation specifies how the linked resource relates to the primary resource. (Examples include “author,” describing a relationship between a resource and its author, or “gc:term,” describing the relationship between a post and its tags or categories.) The relation is either a standardised relation, a URI relation (like https://api.w.org/term`) or a Compact URI relation (like
gc:term). (Compact URI relations can be normalised to full URI relations to ensure full compatibility if required.) This is similar to HTML
tags, or
` links.
链接是一个对象,包含一个带有资源绝对URL的href
属性以及其他可选属性。这些包括内容类型、消除歧义的信息以及有关可以使用链接采取的行动的数据。
对于集合响应(返回对象列表而不是顶级对象的响应),每个项目都包含链接,而顶级响应包括通过Link
头的链接。
注意:
如果您的客户端库不允许访问标头,您可以使用_envelope
参数将标头作为正文数据。
示例响应
一个典型的单个post请求 (/gc/v2/posts/42
):
{
"id": 42,
"_links": {
"collection": [
{
"href": "https://example.com/gc-json/gc/v2/posts"
}
],
"author": [
{
"href": "https://example.com/gc-json/gc/v2/users/1",
"embeddable": true
}
]
}
}
嵌入 Embedding
或者,响应中可能会包含一些链接资源,以减少所需的HTTP请求数量。这些资源被“嵌入”到主要响应中。
Embedding is triggered by setting the _embed
query parameter on the request. This will then include embedded resources under the _embedded
key adjacent to the _links
key. The layout of this object mirrors the _links
object, but includes the embedded resource in place of the link properties.
只有将embeddable
标志设置为true
的链接才能嵌入,_embed
将导致所有可嵌入链接嵌入。_embedded
中仅包含包含嵌入式响应的关系,但与混合可嵌入和不可嵌入链接的关系将包含不可嵌入链接的虚拟响应,以确保数字索引与_links
中的索引匹配。
嵌入集合响应时,例如/gc/v2/posts?author=1
,嵌入的集合将应用默认分页限制。
示例响应
{
"id": 42,
"_links": {
"collection": [
{
"href": "https://example.com/gc-json/gc/v2/posts"
}
],
"author": [
{
"href": "https://example.com/gc-json/gc/v2/users/1",
"embeddable": true
}
]
},
"_embedded": {
"author": {
"id": 1,
"name": "admin",
"description": "Site administrator"
}
}
}