I am studying REST API. I'm thinking about how to design the REST API for the following situations.
"If you click the Like button on a post, increase the number of likes on that post."
This corresponds to an UPDATE among CRUD. Right? Then should I express the URL like this?
POST /post/{post_id}/likes
But there also will be situations like this.
If you press the "Like" button again, Decrease the likes again.'
In that case, would it be appropriate to send a request with this data in the payload?
POST /post/{post_id}/likes
{
countup: False // decrease likes
}
I coudn't think of anything better than this,
but I feel strange that this isn't a very good idea.
I want to design the API to match the convention.
I'd appreciate it if you could give me some better ideas.
CodePudding user response:
If you click the Like button on a post, increase the number of likes on that post. If you press the "Like" button again, Decrease the likes again.
Pressing the like button and adding a toggle is an UI thing.
on a post increase the number of likes or decrease the likes
If it would be operations I would do increaseLikesForPost()
, decreaseLikesForPost()
. What is hidden here that we usually add the session.userid
as a parameter to know which user like the post later, not just increasing the number of like, so what really happens here is increaseLikesForPost(actualUser)
, which does not make much sense in this context. It would be normally just actualUser.like(post)
or post.isLikedBy(actualUser)
. Since we use the API from the viewpoint of the post
it is better to use the latter one.
So how do we translate this: post.isLikedBy(actualUser)
or this: postIsLikedBy(post, actualUser)
to the language of HTTP methods and an URIs?
A possible solution is POST|PUT /api/posts/:postid/likes/:actualuserid
and DELETE /api/posts/:postid/likes/:actualuserid
. If you don't want to add session related data to the URIs like actualuserid
, then it is better to do POST|PUT /api/posts/:postid/like
and DELETE /api/posts/:postid/like
and get the actualuserid
from the Authorzation
header.