0

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
unor
  • 92,415
  • 26
  • 211
  • 360
John Cena
  • 61
  • 6

2 Answers2

0

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.

HTTP includes the concept of redirection - a general facility for telling the client to send a request to some other resource.

GET /714eeebd-d89e-4f13-b2a8-cf8a3ee03481 ...

307 Temporary Redirect
Location: /7604abf9-d4f5-42c7-b687-96dbff32649f

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

/comments

is a perfectly reasonable collection identifier all on its own, and its perfectly reasonable to create an identifier hierarchy under that root.

Community
  • 1
  • 1
VoiceOfUnreason
  • 52,766
  • 5
  • 49
  • 91
0

Below URI should serve the purpose.

/comments

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

To retrieve the posts:

/posts

To retrieve a specific post:

/posts/{post_id}

when you need only comments and just passing comment_id

To retrieve all comments:

/comments

To retrieve specific comment:

/comments/{comment_id}

when you need comments for a given post by passing both post_id and comment_id

To retrieve comments on a post:

/posts/{post_id}/comments

To retrieve specific comment for given post:

/posts/{post_id}/comments/{comment_id}

Hope it solves your issue.