Search code examples
json-apicoding-style

Should JSON API entities include a relationship for its parent?


If we have, say, a blog with posts, and each post can have comments, and each comment a related user. Is it against convention, if I request the comment, to include both the user and the post in the relationships?

data: {
  type: 'comments',
  id: '1',
  relationships: {
    post: {...}, //should this be here?
    user: {...},
  }
  attributes: {...},
},
included: {...}

Solution

  • As paulsm4 correctly stated: "it is up to you".

    But I can give you some advice about that.

    In such situations, you can give the caller of the API the choice of having such links or not via a querystring flag, like

    ?relationships=post,user

    In this case, if you do not specify the relationship flag, you'll get the simple comment data or you can decide to give them all; in the second case, you can use relationships as a sort of filter.

    In some APIs, I've seen also a more invasive approach: embed the related object directly in the returned JSON.

    With the same technique as before:

    ?embed=post,user

    This should produce an embedded JSON object in the current JSON reply including the original objects just as you were asking something like "GET /post/123" or "GET /user/456" separately. This can be handy in some situations.

    Often this flag is named "expand" denoting same or similar behaviour.

    For an example open this API documentation from Atlassian and search for "expand".

    It does exist an old "standard" for your problem called HAL that speaks about linking and embedding in REST APIs.

    Even the Wordpress API offers such features, give it a look in the official documentation.

    An alternative to this is to rewrite the entire API in GraphQL leveraging the REST approach.