I have 2 resources that are Many-To-Many
related.
One resource is users
and the other is roles
. A user
can have different roles
assigned, whereas a role
can have different users
assigned.
/users
will return all users /roles
will return all rolesThe Many-To-Many
relation allows me to use the following resource paths:
/users/1/roles
will return all roles assigned to user with id 1/roles/1/users
will return all users assigned to role with id 1Now let's say I want to assign a role with id 2 to user with id 1.
I have two different ideas:
PUT /users/1/roles/2 (No request body, as no use)
. This approach would be quite readable and clearly idempotent. Also I don't expect a response. But it seems weird not to send a request body with a PUT request.
POST /users/1/roles (Role object as request body)
This approach seems technically more correct. But it's not obvious that I want to map an already existing role. It seems more that I create a role for this user. Also it seems very useless to attach an already existing role to the request. A BadRequest
because I try to add a non-existing role, would be very confusing.
Both seem actually not really correct to me...
How is this done in a understandable REST conform way?
I will use PUT
verb since you are updating the roles assigned to your user.
But I prefer using the request body to specify the full list of roles that I want to assign to this users.
PUT /users/1/roles (list of assigned Role objects as request body)
POST
verb, as you said, is generally used for creating new object.
Also, here are additional advises from colleagues which I find useful: RESTful APIs from Scratch: Lessons Learnt (so far)