gezinspace gezinspace - 4 months ago 15
reST (reStructuredText) Question

Do nested resources need to be paged too?

I'm building a REST api. A simple example of a problem I'm looking to solve involves 2 domain entities: posts & comments. Currently a GET request to http://myapidomain.com/posts returns a collection of posts, where each post contains a link to comments about this particular post. I'm going to also allow the possibility to have the comments link expanded in the response so that the comments list is displayed in line, rather than a url pointing to them. There are pros and cons to each approach, but good reasons to include both options.

My problem is that say for example my GET request to /posts returns a paged list (with a page size of 10, for example) of posts where list of comments are included instead of just a link...do I need to be paging the nested resources too? I'm worried that a single post can have unlimited number of comments, so therefore a list of 10 posts might have one or more posts that have many 100 s of comments for one post. So do inner / nested resources need to be paged too, or is there some standard way to deal with that situation?

Answer

Including a link for a collection sub-resource is a good practice. If the client needs the collection, a new request to the link can be performed.

However, if for some reason, you need some comments pre loaded for each post, I would consider including only the first page of comments and providing a link to load the next page.

{
  "data": [
    {
      "id": 1,
      "title": "It's a post",
      "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit...",
      "comments": {
        "data": [
          {
            "content": "It's a comment",
            "author": "John Doe"
          },
          {
            "content": "It's comment",
            "author": "Jane Doe"
          },
          ...
        ],
        "paging": {
          "next": "http://api.example.com/posts/1/comments?page=2&size=10"
        }
      }
    },
    ...
  ],
  "paging": {
    "previous": "http://api.example.com/posts?page=1&size=10",
    "next": "http://api.example.com/posts?page=3&size=10"
  }
}