What is the importance of the self link in hypermedia APIs?

廉价感情. 提交于 2019-12-06 18:45:08

问题


All the articles and books I read on REST repeat the importance of adding "self" rel links to your hypermedia responses but they're all light on the reasons and use cases.

Why should you add a self link and how is it useful?


回答1:


The main reason is that clients (and even some servers) do not store the location of a representation with the representation. For example, if you wget http://.../foo.json, the representation will be saved to disk, but the URI at which it was fetched will not be. If there is no "self" link embedded in the representation, this causes two problems:

  1. Relative links in the document may no longer have a base against which to resolve, and will therefore be "broken"; and

  2. The client will have no embedded concept of where to e.g. PUT the document back to a server if they modify it. A few clients maintain this information independently, but most do not.

It's important to understand that representations may have a life well outside the HTTP conversation, and may even be transferred via other protocols (e-mail, FTP, in a book, etc). An experienced media-type designer will therefore typically include a "self" link.




回答2:


When a resource is returned, it may not be the full representation. The self link should provide a url to access that full representation

e.g.

GET /objects

[
  {
    "name": "tech",
    "links": [
      "rel": "self",
      "href": "/objects/1"
    ]
  },
  {
    "name": "book",
    "links": [
      "rel": "self",
      "href": "/objects/2"
    ]
  }
]

GET /objects/1

{
  "name": "tech",
  "ratio": 1,
  "precision": 2,
  "links": [
    {
      "rel": "self",
      "href": "/objects/1"
    }
  ]
}      


来源:https://stackoverflow.com/questions/14185011/what-is-the-importance-of-the-self-link-in-hypermedia-apis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!