How to represent a count of relationships instead of including them?


#1

I am fetching a list of resources. Each resource has a “has many” relationship and I need to display its count. However, I don’t want to include all of the IDs of the related resources because it is too much information.

For example, let’s say I am fetching a list of blog posts, and need to display the count of comments. I don’t want to fetch hundreds of comment records just to display the count.

What is the best way to represent this data?


#2

For now, the best way is to put it in the meta object of the relationship object, like so:

{
  "type": "people",
  "id": "1",
  "attributes": { /* some attributes.. */ },
  "relationships": {
    "friends": { 
      "meta": { 
        "count": 32
      },
      // links are optional here, but *strongly* recommended.
      // for the meaning of these links, see 
      // http://discuss.jsonapi.org/t/usage-of-related-field-in-relationships-link/145
      "links": { 
        "self": "http://example.com/people/1/relationships/friends",
        "related": "http://example.com/people/1/relationships/friends"
      }
    }
  }
}

#3

I think this is more complicated. I tried to explain it here: https://github.com/json-api/json-api/issues/1050


#4

@ethanresnick, do you think here is a typo in the links section above with both self and related links pointing to the same end point?