rest - 用于非资源响应的 JSON API

标签 rest api json-api jsonapi-resources

目前,我正在开发新产品并为公共(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/

相关文章:

api - 谷歌云平台 : List available projects using api

javascript - 为什么对 Rails API 的 GET 请求不起作用?

django - 在 ModelViewSet 中返回 422 状态码

javascript - AJAX 调用从我的 REST API 获取 "400 bad request"响应

c# - Android 模拟器没有连接到 localhost api

java - Java 中的 REST POST 方法

ember.js - json 分页资源应该是什么样子?

json - Mongoid 嵌入式文档和 Rails 强参数不起作用

rest - RESTful API路由设计:嵌套与非嵌套

java - 结果 Object/json 包含 Long 字段类型时单元测试 Spring MVC REST Controller