سؤال

Let's say we have two kinds of resources, user and group.
Every user can belong to multiple groups and each group can have many members.
Thus I can model my API like this

/
|_ /users/{id} 
|   |_ groups
|
|_ /groups/{id} 
    |_ members 

Let's say our resources exposes only two actions. You could either add a user to a group or remove one from it.
When it comes to the implementation I could think of two possible requests for each action.
You could PUT a new user in a group's members collection, or PUT a new group in a user's groups collection.

Should I implement both "entry points"? Is this expected in RESTful applications? If not, which one should I implement?

هل كانت مفيدة؟

المحلول

REST doesn't have any expectations on this. You can implement both or only one of them. Also there is a possible third options to have a resource user_group_relation which handles this functionality.

Which one you need or want to implement depends on your needs. If it's for a pure API one should be enough (I would go for adding a member to a group, since this feels more natural).

But if you have a web site or app that offers both options for editing and has two very distinct types of response it may be more comfortable to implement both. Say a user page has a list of groups where you can add groups and at the same time your groups show lists of users where you can add new members. Both lists are very different, both actions would have to return very different responses to update those lists (and maybe more info specific to those pages like number of groups for the user, number of users for the group).

نصائح أخرى

I'd recommend using only one method of adding/removing users in groups. To keep it simple, in a well design API there should be only one path to achieve each action. Moreover, that path should be the shortest possible.

Now to choose what is the right path (PUT /users/{idu}/groups/{idg} or PUT /groups/{idg}/users/{idu}). It's up to you, but I'd rather use the second one. Because it's the answer of who owns who ? Or What is composed of what ?

It is not a dogmatic answer, there could be reasons to choose the first one especially if you you consider the fact that being in group is property of the user.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top