chrisc
chrisc

Reputation: 105

How to associate nested relationships with attributes for a POST in JSON API

According to the spec, resource identifier objects do not hold attributes.

I want to do a POST to create a new resource which includes other nested resource. These are the basic resources: club (with name) and many positions (type). Think a football club with positions like goalkeeper, goalkeeper, striker, striker, etc.

When I do this association, I want to set some attributes like is the position required for this particular team. For example I only need 1 goalkeeper but I want to have a team with many reserve goalkeepers. When I model these entities in the DB I'll set the required attribute in a linkage table.

This is not compliant with JSON API:

{
    "data": {
        "type": "club",
        "attributes": {
            "name": "Backyard Football Club"
        },
        "relationships": {
            "positions": {
                "data": [{
                        "id": "1",
                        "type": "position",
                        "attributes": {
                            "required": "true"
                        }
                    }, {
                        "id": "1",
                        "type": "position",
                        "attributes": {
                            "required": "false"
                        }
                    }
                ]
            }
        }
    }
}

This is also not valid:

{
    "data": {
        "type": "club",
        "attributes": {
            "name": "Backyard Football Club",
            "positions": [{
                "position_id": "1",
                "required": "true"
            },
            {
                "position_id": "1",
                "required": "false"
            }]
        }
    }
}

So how is the best way to approach this association?

Upvotes: 1

Views: 836

Answers (1)

Calin
Calin

Reputation: 6867

The best approach here will be to create a separate resource for club_position

Creating a club will return a url to a create club_positions, you will then post club_positions to that url with a relationship identifier to the position and club resource.

Added benefit to this is that club_positions creation can be parallelized.

Upvotes: 1

Related Questions