json – 链接到REST API中的另一个资源:通过其ID或URL?

栏目: 后端 · 前端 · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/30981727/link-to-another-resource-in-a-rest-api-by-its-id-or-by-its-url
我正在使用 apiary

创建一些API,因此使用的语言是JSON.

我们假设我需要代表这个资源:

{
    "id" : 9,
    "name" : "test",
    "customer_id" : 12,
    "user_id" : 1,
    "store_id" : 3,
    "notes" : "Lorem ipsum example long text"
}

通过ID(12,1,3)引用其他资源是否正确,或者我应该指定这些资源的URL(即/ customers / 12,/ users / 1,/ stores / 3)?

我没有使用HATEOAS,我有点困惑.

请在您的回复中包含 absolute

个实体URI(例如/ customers / 12或甚至http://www.example.com/customers/12).

不要在响应中仅包含实体的ID(例如12),因为这样会迫使客户自己组合资源URI.为了做到这一点,他们需要事先知道有什么URI,并且你失去了对服务器端URI空间的控制.

(如果服务器指示客户端如何,例如通过发送 URI template 以及ID,则客户端将URI组合在一起;但如果它这样做,它也可以发送生成的URI.)

也可以看看:

> Article “REST APIs must be hypertext-driven” by Roy T. Fielding (REST的创始人).特别注意这两个要点:

  • “A REST API should be entered with no prior knowledge beyond the initial URI (bookmark).”
  • “A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). Servers must have the freedom to control their own namespace. Instead, allow servers to instruct clients on how to construct appropriate URIs[.]”

> HAL ,它指定了将相关资源的链接放入响应的标准方法.

> JSON API – “使用JSON构建API的规范”

>以上建议不仅适用于其他资源的ID(即您的customer_id等“外键”);你也将资源自己的id变成了所谓的“自我链接”;见 SO question “What is the importance of the self link in hypermedia APIs?” .

例:

您的原始资源可以按如下方式重新设计:

{
  "type": "foobar",
  "id": "9",
  "links": {
    "self": "//example.com/foobars/9"
  },
  "cashier": {
    "type": "user",
    "id": "1",
    "links": {
      "self": "//example.com/users/1"
    }
  },
  "customer": {
    "type": "customer",
    "id": "12",
    "links": {
      "self": "//example.com/customers/12"
    }
  },
  "name" : "test",
  "notes" : "Lorem ipsum example long text",
  "store": {
    "type": "store",
    "id": "3",
    "links": {
      "self": "//example.com/stores/3"
    }
  }
}

有几点需要注意:

>每个资源(正在传输的主要对象,还有子资源)都附加了一些自描述元数据,例如type,id,links.

>子资源可以包括部分或完整数据.只要有自我链接,客户端就知道从哪里获得完整的资源.

>这种类型似乎有点减少;通常,你隐含地知道期望什么样的对象.此属性可以帮助验证,并且还使您有机会区分对象类型和角色(例如,出纳员是上例中的用户).

翻译自:https://stackoverflow.com/questions/30981727/link-to-another-resource-in-a-rest-api-by-its-id-or-by-its-url


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Real-Time Rendering, Third Edition

Real-Time Rendering, Third Edition

Tomas Akenine-Moller、Eric Haines、Naty Hoffman / A K Peters/CRC Press / 2008-7-25 / USD 102.95

Thoroughly revised, this third edition focuses on modern techniques used to generate synthetic three-dimensional images in a fraction of a second. With the advent or programmable shaders, a wide varie......一起来看看 《Real-Time Rendering, Third Edition》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具