I am trying to get my head around how to handle relationships in REST.
I have read this question.
If I have Drivers and Cars in my api and a Driver can only exist if connected to a Car I would make Drivers a subresource in Cars. The relationship between a Car and a Driver contains a set of properties, say averageSpeed
and timeOnTheRoad
. One Car can have many Drivers, but a Driver can only have one Car.
How should I add a new driver? How should I add a relationship between a driver and a car?
If I add a resource Wunderbaums which is not a subresource to Cars, but a Car can contain Wunderbaums. How should I add a relationship between a Car and a Wunderbaum?
One way of adding a relationship between two entities is to POST to /entityA/{id}/entityB/{id}
and send properties for the relationship in the body. This would work for my example with Cars and Wunderbaums since Wunderbaums is not a subresource of Cars, but it would not work in my example with Cars and Drivers since it would interfere with CRUD functionality for Drivers. The path cars/{id}/drivers{id}
would be the same for creating a relationship between a Car and a Driver as for creating a Driver.
I also found this unanswered question on the subject.
Edit 1
@JB Nizet suggested that I put the relationship properties inside of the Driver, since its a one to many relationship. It would be a possible solution, but what if a Driver could have many Cars? Should we handle one to many relations different than many to many relations?
Edit 2
We could put relationship properties with the Driver in a many to many relationship scenario as well. The question then is if Driver has its own resource, is it ok that cars/2/drivers/4
returns a different set of properties than drivers/4
? In the case where I get the Driver by its relation to Car I will include avrageSpeed
and timeOnTheRoad
in the response.