Arū*_*kas 5 api rest json-api jsonapi-resources
目前,我正在研究新产品,并为公共和内部需求制作REST API。我从{json:api}规范开始,对它感到非常满意,直到遇到一些无法找到答案的问题。
根据JSON API规范,每个资源都必须包含id。
每个资源对象必须包含一个id成员和一个type成员。id和type成员的值必须是字符串。
在很多情况下都可以,但不是全部。
我们的大多数端点都是关于“资源”的
如果我要收集“东西”(http://example.com/things)
{
"data": [{
"type": "things",
"id": "1",
"attributes": {
"title": "first"
},
"links": {
"self": "http://example.com/things/1"
}
}, {
"type": "things",
"id": "1",
"attributes": {
"title": "second"
},
"links": {
"self": "http://example.com/things/2"
}
}]
}
Run Code Online (Sandbox Code Playgroud)
如果我只要求一个“物”资源(http://example.com/things/1)
{
"data": {
"type": "things",
"id": "1",
"attributes": {
"title": "first"
},
"links": {
"self": "http://example.com/things/1"
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是如何处理与资源无关且没有ID的终结点呢?
例如,在我们的应用程序中,存在一个端点http://example.com/stats,该端点应返回当前登录用户user的统计信息。喜欢
{
"active_things": 23,
"last_login": "2017"
}
Run Code Online (Sandbox Code Playgroud)
此“资源”没有ID(实际上不是资源,对吗?)。后端只是为登录用户收集一些“统计信息”,并返回一个统计信息对象。在此应用程序中有许多类似这样的端点,例如,我们有“ 通知中心”页面,用户可以在其中更改不同通知的电子邮件地址。
因此,前端应用程序(single-page-app)首先必须获取当前值,然后将请求发送到GET http://example.com/notification-settings。
{
"notifications_about_new_thing": "arunas@example.com",
"notification_about_other_thing": "arunas@example.com"
}
Run Code Online (Sandbox Code Playgroud)
还有更多这样的端点。问题是-如何以JSONAPI格式返回这些响应?这些端点中没有ID。
最大的问题是-为什么没有其他人面临这个问题(至少我找不到关于此的任何讨论)?:D我做过的所有API都有一些没有“ id”的端点。
我有两个想法,第一个是伪造的id,例如"id": "doesnt_matter",第二个-不要json-api用于这些端点。但是我不喜欢他们两个。
以 REST 方式思考,一切都可以(必须)成为资源。没有“登录”用户,因为 RESTful API 中没有会话,因为它们是无状态的。在 REST API 调用之间没有维护会话状态,因此您必须明确用户是谁。
在这种情况下,资源是具有某些 stats 属性(在简单情况下)或可能与单独的 stats 关系(更复杂,未显示)的关系的用户:
GET /users/1234
{
"data": {
"type": "users",
"id": "1234",
"attributes": {
"name": "etc.",
"active_things": 23,
"last_login": "2017"
}
}
}
| 归档时间: |
|
| 查看次数: |
962 次 |
| 最近记录: |