Rest API - Friends collection creation
-
02-07-2021 - |
Question
Users can basically add other user(s) as a friend. So, I am not creating another user resource but linking two resources.
Questions
- What is the best strategy to handle this?
- What is the appropriate Verb for this case?
I heard there is a LINK
verb, which seems to be appropriate.
And also I read, I can use PATCH
verb to apply patch on resource(s).
If so, can I do like this
PATCH /users/{id}/friends
Solution
You might consider creating a new object.
If you separated out a friendship
object, you would be able to create and modify them without updating the User(s). Each friendship would have two user keys. It would also be a great place to hang extra information about the friendship, such as 'friends since' value.
POST /friendships
{
primaryUser: 43,
secondaryUser: 3
since: "03/16/2010"
}
201 CREATED
location: /friendships/635
Then a query to user 43 could be written to include an array of either user ids, friendship ids, or embedded objects.
GET /users/43
200 SUCCESS
{
id: 43,
name: "john",
friends: [3]
}
Or
200 SUCCESS
{
id: 43,
name: "john",
friends: [635]
}
or
200 SUCCESS
{
id: 43,
name: "john",
friends: [
{
id: 635,
primaryUser: 43,
secondaryUser: 3,
since: "03/16/2010"
}
]
}
Semantics for updating/removing are much more straight forward. 'Removing' a friendship looks better as a DELETE
rather than a PATCH
or PUT
imo.
OTHER TIPS
"Linking a resource" really just means "update one resource to include a link to another".
That means that you should issue a PUT or POST to resource A with a new representation that includes the new reference to resource B.
If it's a bi-directional relationship then by virtue of making that PUT/POST on resource A you should also see the reference to A included the next time you GET resource B, too.