How to model to-many relationships so individual pivot table records can be updated?

I’m trying to adhere to the JSON API spec to build out an API for user relationships. There’s a many-to-many relationship between users, and I have a pivot table called user_relationships that holds a composite key of two user IDs as well as a status code column to define the “state” of the relationship.

In order to create a relationship between users, I was making a POST request to a to-many relationship link: /api/users/{user}/relationships/users. This worked great, until I realized that I’d be unable to update the state of this relationship per the spec (I think?). In order to update the state of the relationship, I’d submit a PATCH request to update a specific relationship status, but in reading the spec it looks like PATCH requests to to-many relationships are just for replacing all of the relationships with the provided data. No way to partially update just a single relationship.

So I started to wonder if I should build out my user relationships as an actual resource user-relationships. With this I’d make a POST request to /api/user-relationships, but I’d obviously need to specify the two user IDs that I need to connect, and I don’t know where those would go inside my request data. This doesn’t seem right though since the IDs of another resource are in the attributes:

{
  "data": {
    "type": "user-relationships",
    "id": "1234",
    "attributes": {
      "requester_id": "1",
      "recipient_id": "2"
    }
  }
}

Or maybe

{
  "data": {
    "type": "user-relationships",
    "id": "1234",
    "relationships": {
      "users": {
        "data": [
          {
            "type": "users",
            "id": "1",
            "meta": {
              "type": "requester"
            }
          },
          {
            "type": "users",
            "id": "2",
            "meta": {
              "type": "recipient"
            }
          }
        ]
      }
    }
  }
}

So I’m wondering how you guys might model this to work with the JSON API spec. I’m not sure if an entirely new resource that is really just representing a pivot table is the way to go, or if I’m missing something when it comes to to-many POST/PATCH requests, but any insight would be greatly appreciated!

P.S. I posted a question yesterday that I removed since my question has changed to what is above.

1 Like