What is the point of link rel=“self” in a REST API?
https://softwareengineering.stackexchange.com/questions/230157
سؤال
I often see the following in HTML documents
<link rel="self" href="http://example.com/something">
or like this in JSON
link: {
rel="self",
href="http://example.com/something"
}
or in XML
<atom:link rel="self" href="http://example.com/something" />
So I had some questions:
- Why include this link? What advantage does it bring? (Please tell me there is a reason to it and its not just a "good practice" talisman)
- How should I exploit this link in my clients? What are the use case for this link?
- When shouldn't I use this link? When is it pointless to include it?
المحلول
It is a self reference, so the client will know that the IRI (http://example.com/something
) is an identifier of the resource the representation is about.
It can be important when your resource can have multiple identifiers, for example http://example.com/users/1
and http://example.com/users/1?fields="name"
can identify the same resource, but a GET on them can result different representations.
By media types like HAL you use this to identify embedded resources as well. For example:
{
"nick": "John",
"_embedded": {
"cars": {
"items": [
//...
],
"_links": {
"self": {
"href": "http://example.com/users/john/cars"
}
}
}
},
"_links": {
"self": {
"href": "http://example.com/users/john"
}
}
}
لا تنتمي إلى softwareengineering.stackexchange