Which HTTP verb is appropriate for setting a boolean?
I have a RESTful web service which exposes a resource that enables you (the logged in user) to like or unlike a blog post. My question is: what is the RESTfully correct way to express this resource?
My first stab looks like:
PUT /likes/<blog_entry_id> # marks this blog entry as liked
DELETE /likes/<blog_entry_id> # marks this blog entry as not liked
This semantic is at least consistent with the idempotency requirements of PUT and DELETE (i.e. repeated calls to PUT have no effect unless interspersed with DELETEs, and vice versa).
Is there a more conventional design for the 开发者_StackOverflowmanagement of a boolean HTTP resource?
You need to include some kind of user identification within your URI. By using the "logged in user" you are violating the resource identification constraint and the self-description constraint.
The only other issue is you seem to be using PUT without passing a body. I've never seen that done before. It's quite possible the HTTP spec allows for it, it is just a bit strange.
I think your approach is fine and restful. You can also use POST instead of PUT.
I would step away from using verbs in resource URLs and use the following schemes:
POST /blog/<id>/fan
Send the user-id and other data for the resource you want to create as part of the 'Like' action. I'm supposing JSON here, so this could be an example { "user": "http://..../user/34343", "timestamp": 234353443 }
you could then use
GET /blog/<id>/fan
to get a list of all users that like the blog post. I would probably send a JSON presentation of the resource that makes it easy to list those users and follow a link the the data of the like action (if there is any)
GET /blog/<id>/fan/<user-id>
to get the data of the like action (if there is any)
In a relational database I would call this a good candidate for a join table.
LIKES ----- id blog_id user_id some_other_attribute_about_this_relationship another_attribute timestamp
So what you're creating is a Like, or a Fan, or BlogLike, or BlogFan, or a BlogLiker, or, you know, fan_of_a_blog, if you're not into the whole brevity thing.
So these are your verbs:
GET /likes return a list of Likes POST /likes create a new Like (payload is blog_id and user_id) GET /likes/id return a specific Like resource PUT /likes/id update a Like with new data DELETE /likes/id delete a Like
This will allow you to ask questions on either side of the join. E.g., Does this user like a certain blog? Is this blog liked by more than 3 users? Et cetera.
精彩评论