I am designing a REST API with similar functionality as of Posts and Comments in Facebook.
URI looks like:
/posts/{post-id}/comments/{comment-id}
To get all the comments I use the collection URI naming standard. For example:
/posts/{post-id}/comments
But I am having difficulty when I need comments for all the posts. What would be the best way to incorporate that keeping in mind that I want to use this design only for posts and comments?
Edit
I have to mention here that the resources I am using are a bit different from posts and comments in a way that the in my design I will have to use posts and cannot have comments as entirely different entity. Sorry for the misunderstanding.
Said that, is it recommended to design URI in any of these ways:
/posts//comments
/posts/"any-string"/comments
2
Answers
HTTP includes the concept of redirection – a general facility for telling the client to send a request to some other resource.
What this means is that, if you choose the wrong spelling for your URI, you can correct it later.
The design of REST is such that identifiers are opaque – nobody other than the server is supposed to be extracting information from them.
Also, keep in mind that resources are not domain entities — it’s normal to have many more resources than you have domain objects. Any given Post in your domain model might have many different resources that show it.
If you are really developing a REST service, and you want to "help" clients by making it difficult to cheat, you may want to abandon the idea of using a hackable identifier.
All that said
is a perfectly reasonable collection identifier all on its own, and its perfectly reasonable to create an identifier hierarchy under that root.
Below URI should serve the purpose.
For the above given example, let’s understand the relationship of entities and URI:
posts and comments are two entities on its own.
when you need only posts and just passing post_id
when you need only comments and just passing comment_id
when you need comments for a given post by passing both post_id and comment_id
Hope it solves your issue.