休息 - 关系上下文 [英] rest - relation context
问题描述
假设我有两个收藏资源:
Say I have two collection resources:
/persons
/organizations
A GET
到 /persons/id/
返回一个特定的人.同样,对 /organizations/id
的 GET
返回一个特定的组织.
A GET
to /persons/id/
returns a specific person. Likewise, a GET
to /organizations/id
returns a specific organization.
一个人可以是一个或多个组织的成员.在这种关系上下文中,我们拥有诸如此人在组织中的角色、此人加入组织的日期等数据......
A person can be member of one or more organizations. In this relation context, we have data such as the role of the person in the organization, the date on which the person joined the organization, ...
哪种设计最有意义?
成员资源
/memberships/id
,GET
向其返回关系上下文的数据(以及指向个人和组织的链接)).
A membership resource
/memberships/id
, to which aGET
returns the data of the relation context (together with a link to the person and the organization).
一个 /persons/id/organizations/id
和一个 /organizations/id/persons/id
.对两者之一的 GET
返回关系上下文,对另一个的 GET
重定向(http 状态代码 303)到另一个.
A /persons/id/organizations/id
and a /organizations/id/persons/id
. A GET
to one of the two returns the relation context, and a GET
to the other one redirects (http status code 303) to the other.
还有什么?
推荐答案
另一种选择是将关系直接嵌入到资源本身中.这使得客户端在使用服务时更容易跟踪资源之间的关系.例如,这里有一个假设的 person
,它通过两个 membership
资源和其中一个 membership
资源与两个 organization
资源建立了关系> 资源:
Another option is to embed the relationships right into the resources themselves. This makes it easier for a client to follow relationships between resources as they consume the service. For example, here's a hypothetical person
with relationships to two organization
resources via two membership
resources, and one of those membership
resources:
"person890": {
"firstName": "Jane",
"lastName": "Smith",
"links": [{
"rel": "membership",
"href": "memberships/123"
}, {
"link": "membership",
"href": "memberships/456"
}]
}
"membership123": {
"role": "chairwoman",
"date: "12/23/2013",
"term": "3 years",
"links": [{
"rel": "person",
"href": "persons/890",
}, {
"rel": "organization",
"href": "organizations/7575"
}]
}
这里的基本原则是HATEOAS - 超媒体作为应用程序状态的引擎"- 这使对您的数据了解最少的客户仍然可以与您的 API 进行交互.
The basic principle at work here is HATEOAS - "Hypermedia as the Engine of Application State" - which enables a client with minimal understanding of your data to still interact with your API.
这篇关于休息 - 关系上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!