json - 为同一个请求返回不同的 JSON 结果——这是否违反了 REST?

标签 json rest

请注意以下来自 Roy Fielding 的关于 REST 设计、指南和原则的内容。

5.2.1.1 Resources and Resource Identifiers

The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource.

A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.

More precisely, a resource R is a temporally varying membership function MR(t), which for time t maps to a set of entities, or values, which are equivalent. The values in the set may be resource representations and/or resource identifiers. A resource can map to the empty set, which allows references to be made to a concept before any realization of that concept exists -- a notion that was foreign to most hypertext systems prior to the Web [61]. Some resources are static in the sense that, when examined at any time after their creation, they always correspond to the same value set. Others have a high degree of variance in their value over time.

The only thing that is required to be static for a resource is the semantics of the mapping, since the semantics is what distinguishes one resource from another.

关键点已加粗,我包含的其余段落是为了上下文。

这是场景。

我有一个具有端点的网络 API:http://www.myfakeapi.com/people

当客户端向此端点发出 GET 请求时,他们会收到一个人员列表。

Person
{
  "Name": "John Doe",
  "Age": "23",
  "Favorite Color": "Green"
}

好的,那太好了。

但是如果我有一个没有最喜欢的颜色的“人”并且我想像这样返回它们,这是否违反 REST 设计实践和原则:

Person
{
  "Name": "Bob Doe",
  "Age": "23",
}

或者我应该这样归还它们:

Person
{
  "Name": "Bob Doe",
  "Age": "23",
  "Favorite Color": null
}

问题是请求资源的客户端必须做额外的工作来首先查看该属性是否存在。有些“人”有最喜欢的颜色,有些则没有。如果“最喜欢的颜色”的 json 属性不存在,则仅省略它们是否违反 REST 原则 - 还是应该为该属性赋予“空”或空白值?

REST 对此有何看法?我在想我应该返回一个空值,而不是通过省略属性来更改客户端请求的资源的表示。

最佳答案

我想不出这违反了任何 REST 约束(如果您有兴趣,这里有一个指向 brief overview 的链接)。它也不违反 GET 请求的幂等性。但是,这仍然是不好的做法

您的 API 的使用者应该知道会发生什么,理想情况下,这应该有详细的记录(为此我非常喜欢使用 Swagger)。预期内容的任何更改都应传达给消费者,可能采用发行说明的形式。可能会破坏您的消费者的更改应该在新版本的 API 中提供。

由于您的 Person1 和 Person2 在技术上是不同的对象结构,因此它们本身可能会崩溃(让我们面对现实吧,作为开发人员,我们并不总能找到边缘情况)。您不只是希望您的 API 在基本级别上工作并让最终用户见鬼去吧 - 您希望在设计它时考虑到最终消费者,以便他们的生活更轻松。

关于json - 为同一个请求返回不同的 JSON 结果——这是否违反了 REST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59888251/

相关文章:

c# - XML 字符串到 c# 对象不返回数据

javascript - 使用 KnockoutJS 将 JSON 对象映射到 View 模型的一部分

python - 如何从 Bottle 中的路径获取参数?

java - 是否有类似 javadoc 的工具可以从 JAX-RS 注释生成 RESTful Web 服务 apidoc?

android - 移动设备上出现 404 错误,但在 PC 浏览器上有效

c# - 是否可以使用 jquery 将文件上传到 SharePoint 文档库?

java - JSON Android java.lang.NullPointerException

json - Node.js SOAP 客户端参数格式化

javascript - 在js中用<string, object>实现 "like"HashMap

java - @JsonIgnore 不适用于 Spring Boot 应用程序