REST API:returns 的公共资源模型(包装器)

REST API : Common Resource Model (Wrapper) for returns

总结:API 调用的 returned 对象与必须从调用者提交的对象不同是否可以。

让我举例说明:

给定两个 API:食物 & 运动(资源),都具有标准的 CRUD 操作,并且其签名是标准的。

示例:

调用 PUT / POST 要求负载包含对象模型,例如FoodModelSportModel

问题是:让所有调用 (GET/POST/PUT/DELETE) return 具有嵌套对象的通用数据模型有什么问题,该嵌套对象在需要时具有序列化资源。

Example of required model to be sent from caller for POST .../sport

{
  name: "soccer",
  popularity : "high"
}

Example of return model for GET .../sport/{1}

( !GET return,不是来自 POST 的响应(认为它也可能是一个 TransactionModel)

{ "TransactionModel":{
                      correlationId: "83abaf27-3e87-43e5-a4ae-29eda793aff5",
                      anotherProperty1 : "...",
                      anotherProperty2 : "...",
                      resourceType : "Sport"
                      resourceValue : {
                                  name : "Soccer",
                                  popularity: "high",
                                  createdDate: "2019-06-05 23:06:32.923"
                                 }

}

所以澄清一下,调用这些端点需要在负载中使用它们各自的模型(对于 POST 和 PUT),所以 SportModel / FoodModel

我的响应对象是一个 TransactionModel,其中包含所需的资源模型。 所有资源(运动、食物、规则、人物等)都会发生这种情况

如果您有任何文章、RFC 文档或任何支持或反对此方法的内容。还请提供。

谢谢

The question is: Is there anything wrong with having all calls (GET/POST/PUT/DELETE) return a common datamodel who has a nested object that has the serialized resource where needed.

简答:否

稍微长一点的回答:不,不是在理想情况下。但那样也不是不可以弄得乱七八糟。

万维网是 REST 架构风格的参考应用程序。 HTML 文档通常作为资源的表示形式交付,您可能会注意到可能有相当数量的...仪式?...在​​与以下内容没有直接关系的 HTML 文档中资源状态。

让我们面对现实吧——无论您的表示是什么,该表示本身都会嵌入到 HTTP 消息中,携带它自己的元数据。

重要的是客户端和服务器对表示的语义有共同的理解。更好的是,如果这种共同理解被设计成可以以 backwards/forwards 兼容的方式轻松扩展。

在架构上,资源不限于一种且恰好是一种表示。因此,您可以选择同时支持 application/jsonapplication/prs.my-custom-app+json,为那些有足够能力提出要求的客户提供更丰富的实现。

Are you suggesting that if the "Accept" header was only specified for "application/json" the response would be the expected model of the resource, e.g. SportModel. Where as "application/pry.my-custom-app+json" would return the "TransactionResult" model?

是的,与请求 text/plain 的客户端可能获得与请求 text/html.

的客户端不同的资源表示方式完全相同

这里有一个 2008 comment from Roy Fielding 可能会让您更清楚地了解它的来源

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

没有!你没有做错任何事。

但我更喜欢为每个请求和响应使用不同的表示对象,因为在项目的初始阶段它看起来很酷,但随着时间的推移,对 GET response/request 或说 POST 的要求有所不同response/request 这会弄乱您的代码,因为您将尝试使用通用数据模型或表示对象来处理这些事情。

我以前和你做的一样,但随着时间的推移我学会了。它会增加你现在的工作,但会让你未来的发展变得容易得多。