Create/update relationships with attributes

Hello,

after reading specification, I’m a bit confused about creating/updating resources with relationships that contains attributes. Let’s say I need to create new resource with relationship that has attributes, I’d do it like this:

{
    "data": {
        "type": "carts",
        "attributes": {
            note: "Some note about cart",
         },
         "relationships": {
             "products": [
                  {
                      "data": {  
                          "type": "products",
                          "id": "10",
                          "attributes": {
                              "quantity": 5
                          }
                      }
                  }
              ]
         }
    }    
}

Althouth I could not find this stated explicitly (maybe I’ve missed it), but for me it seems they way to do this. Am I correct about it?

Thanks in advance for your replies! :slight_smile:

I get what you are trying to do but unfortunately that’s not supported by spec.

The data value of a relationship object must only be a resource identifier objects (has-one) or an array of resource identifier objects (has-many). Using a resource object is not supported. These ones may only be linked by the resource identifier objects. Therefore this feature is called resource linkage.

I get from your example that you are trying to put additional information on the relationship itself. You could model that as meta information using a meta object but I would not recommend this. This goes against the intend of the specification and updating a meta information is not covered by spec.

I would recommend to add an intermediate model, e.g. cart-items which has a relationship to carts and products and a quantity attribute.

Unfortunately JSON:API spec does not support creation of multiple resources with one request yet. So you would need to create the cart and it’s cart-items with separate requests. This limitation should be solved by a new feature called operations, which is proposed for v1.2.

1 Like

@jelhan thanks a lot for your reply! :slightly_smiling_face:

I believe there’s nothing forbidding the client to use the included top-level member. Would you agree the following is valid?

{
    "data": {
        "type": "carts",
        "attributes": {
            "note": "Some note about cart",
        },
        "relationships": {
            "products": [
                "data": {
                    "type": "products",
                    "lid": "some-uuid"
                }
            ]
        }
    },
    "included": [
        {
            "type": "products",
            "lid": "some-uuid",
            "attributes": {
                "quantity": 5
            }
        }
    ]
}