目前,我正在开发新产品并为公共(public)和内部需求制作 REST API。我从 {json:api} 规范开始,我对它非常满意,直到我遇到一些我找不到答案的问题。
根据 JSON API 规范,每个资源 必须 包含 id
.
http://jsonapi.org/format/
Every resource object MUST contain an id member and a type member. The values of the id and type members MUST be strings.
这在很多情况下都很好,但不是全部。
我们的大多数端点都是关于“资源”的
如果我要一个“东西”集合(
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"
}
}]
}
如果我要求一个“事物”资源(
http://example.com/things/1
){
"data": {
"type": "things",
"id": "1",
"attributes": {
"title": "first"
},
"links": {
"self": "http://example.com/things/1"
}
}
}
但是如何处理与资源无关且没有 ID 的端点呢?
例如,在我们的应用程序中,有一个端点
http://example.com/stats
应该返回 的统计信息当前登录用户 .像{
"active_things": 23,
"last_login": "2017"
}
这个“资源”没有 id(它实际上不是资源,是吗?)。后端只是为登录用户收集一些“统计”并返回一个统计对象。在这个应用程序中有很多这样的端点,例如,我们有通知中心页面,用户可以在其中更改不同通知的电子邮件地址。
因此前端应用程序(单页应用程序)首先必须获取当前值并将请求发送到
GET http://example.com/notification-settings
.{
"notifications_about_new_thing": "arunas@example.com",
"notification_about_other_thing": "arunas@example.com"
}
还有更多这样的端点。问题是 - 如何以 JSONAPI 格式返回这些响应?这些端点中没有 ID。
最大的问题是 - 为什么没有其他人面临这个问题(至少我找不到任何关于这个的讨论)? :D 我做过的所有 API 都有一些没有“id”的端点。
我有两个想法,第一个是假
id
,如 "id": "doesnt_matter"
,第二个 - 不要使用 json-api
对于这些端点。但我不喜欢他们两个。
最佳答案
以 RESTful 的方式思考,一切都可以(必须)成为一种资源。没有“登录”用户,因为 RESTful API 中没有 session ,因为它们是无状态的。在 REST API 调用之间没有维护 session 状态,因此您必须明确用户是谁。
在这种情况下,资源是具有一些统计属性的用户(在简单的情况下)或者可能与单独的统计关系有关系(更复杂,未显示):GET /users/1234
{
"data": {
"type": "users",
"id": "1234",
"attributes": {
"name": "etc.",
"active_things": 23,
"last_login": "2017"
}
}
}
关于rest - 用于非资源响应的 JSON API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49754327/