Way to include multiple relationships with same id and type in jsonapi

953 views Asked by At

I have this requirement of fetching data from database based on id. This record can have multiple values for same id and type since it is of type history. The versions however that we use change everytime. Sample of what I want and what I am getting are as below. I am using Java8, rest-api and json api where I mark relationship attributes with annotations. This data is saved and fetched from database, so to be entirely unique row, the id and version combination should be unique. Which means records with same id present in database but with different versions

What I want:

{
  "data":{
        "id": "123",
        "attributes":{
             "name": "SJ"
         },
         "relationships":{
            "contact":{
                    "data":[
                            {
                            "type":"test",
                            "id":"4567"
                             },
                             {
                              "type":"test",
                               "id":"4567"
                             }
                      ]
             }
          }

  },
"included":[
          {
           "type":"test",
           "id":"4567",
           "attributes":{
                  "testfield":"testfield 1",
                  "version": 0
            }
          },
          {
           "type":"test",
           "id":"4567",
           "attributes":{
                    "testfield":"testfield 2",
                    "version":1
             }
          }
  ]
}

What I get:

{
  "data":{
        "id": "123",
        "attributes":{
             "name": "SJ"
         },
         "relationships":{
            "contact":{
                    "data":[
                            {
                            "type":"test",
                            "id":"4567"
                             },
                             {
                              "type":"test",
                               "id":"4567"
                             }
                      ]
             }
          }

  },
"included":[
          {
           "type":"test",
           "id":"4567",
           "attributes":{
                  "testfield":"testfield 1",
                  "version":1
            }
          }
  ]
}
1

There are 1 answers

0
jelhan On

You can not reference two different objects by the same combination of type and id:

Within a given API, each resource object’s type and id pair MUST identify a single, unique resource.

https://jsonapi.org/format/#document-resource-object-identification

For versioned resources, you may want to generate unique IDs for each version by combining the identifier of the resource with the version number.