Search code examples
jsonserializationjson-api

Should I remove `included` models that are already in `data` in a JSON API response?


Let's suppose I have a model called topics which is self-referenced (a topic belongs to a topic via its parent_topic_id).

So, I have a topic called sports and a children topic called basketball.

The JSON API response is currently being serialized as:

{
  "data": [
    {
      "type": "topics",
      "id": "sports",
      "attributes": {
        "name": "Sports",
        "show-role-title": null,
        "created-at": "2017-04-16T21:19:25.000Z",
        "updated-at": null
      },
      "links": {
        "self": "/topics/sports"
      }
    },
    {
      "type": "topics",
      "id": "sports-basketball",
      "attributes": {
        "name": "Basketball",
        "show-role-title": null,
        "created-at": "2017-04-16T21:19:25.000Z",
        "updated-at": null
      },
      "relationships": {
        "parent-topic": {
          "data": {
            "type": "topics",
            "id": "sports"
          }
        }
      },
      "links": {
        "self": "/topics/sports-basketball"
      }
    }
  ],
  "included": [
    {
      "type": "topics",
      "id": "sports",
      "attributes": {
        "name": "Sports",
        "show-role-title": null,
        "parent-topic-id": null,
        "created-at": "2017-04-16T21:19:25.000Z",
        "updated-at": null
      },
      "links": {
        "self": "/topics/sports"
      }
    }
  ]
}

Now, considering that sports is already in data but also related to basketball, is it valid to also attach it as an included record?


Solution

  • In this case you should be having two resources /topics and /parentTopic and it is valid to have the same copy of data in both primary object and included object provided that your request has such necessity. In your case the request will be /topics?include=parentTopic

    According to JSON API spec, include is not mandatory. My suggestion is that /topics is fine and you can refer parent-topic data from /topics relationship (depends on client framework) and if you query particular resource record, you can add inclusion /topics/sports-basketball?include=parentTopic