Home > Mobile >  HATEOAS links best practices
HATEOAS links best practices

Time:09-17

I am working with a REST api that follows a standard that defines that the response should include self, previous, next, and last page links.

{
  "links" : {
    "self" : {
      "href" : "https://myhost/api/2"
    },
    "prev" : {
      "href" : "https://myhost/api/1"
    },
    "next" : {
      "href" : "https://myhost/api/3"
    },
    "last" : {
      "href" : "https://myhost/api/4"
    }
  },

What is the best practice to handle the cases where one or more of the links is redundant such as

  • There is only 1 page (should there only be a self and last link?)
  • You are on the last page (should there be a next link?)

In cases like these should the links that are reduntant be removed? Or should they be set to the current page?

For example if there is only one page should i prefer

{
  "links" : {
    "self" : {
      "href" : "https://myhost/api/1"
    },
    "prev" : {
      "href" : "https://myhost/api/1"
    },
    "next" : {
      "href" : "https://myhost/api/1"
    },
    "last" : {
      "href" : "https://myhost/api/1"
    }
  },

Or

{
  "links" : {
    "self" : {
      "href" : "https://myhost/api/1"
    },
    "last" : {
      "href" : "https://myhost/api/1"
    }
  },

CodePudding user response:

It's perfectly reasonable to have multiple link relations that target the same resource.

It's significantly less reasonable to include link relations with garbage data just to preserve a consistent pattern.

200 OK
Content-Type: application/json
Content-Location: /1

{
  "links" : {
    "self" : {
      "href" : "/1"
    },
    "first" : {
      "href" : "/1"
    },      
    "next" : {
      "href" : "/2"
    },
    "last" : {
      "href" : "/2"
    }
  }
}

Here, it's perfectly reasonable that self and first, link relations with different semantics, have the same target. Similarly, it's perfectly reasonable that next and last have the same target when we happen to be one page from the end of the line.

But the semantics of the prev link relation don't make sense for a page that is already at the head of the line.

Similarly,

200 OK
Content-Location: /this-collection-has-only-one-item
Content-Type: application/json


{
  "links" : {
    "self" : {
      "href" : "/this-collection-has-only-one-item"
    },
    "first" : {
      "href" : "/this-collection-has-only-one-item"
    },      
    "last" : {
      "href" : "/this-collection-has-only-one-item"
    }
  }
}
  •  Tags:  
  • rest
  • Related