10

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:

  1. 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)
  2. How should I exploit this link in my clients? What are the use case for this link?
  3. When shouldn't I use this link? When is it pointless to include it?
  • 3
    "Click here to bookmark this page" would be a use case where you could utilize the "self" reference. More generally, because REST is stateless, the server has no way of knowing from where the request came, so it is entirely possible that the page it returns to will need to know its own URI. – Roger Feb 24 '14 at 18:01
  • Seems like this comment would make a pretty good answer :) – Mike Chamberlain Mar 10 '14 at 11:14
8

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"
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.