Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating "fake" ids in REST API

I have a list of Post entities, and each post have a list of Comment entities. The Post entity is a composition object. No comments exists in the system without a post.

Example of URI:

/posts/3453/comments/8547

This retrieves a particular comment, and is also used to delete and update a particular comment. Now, wouldn't it be better if my API had something like this:

/posts/3453/comments/1

Where the comment id 8547 in the first URI is the same as the last, but the id is in the context of the post. It starts from one and increments as more comments are added. However, if you had 10 comments with id 1-10, then deleting number 5, should it update the ids in some way so that 1-9 applies?

Does this even sound reasonable? I just started to think of it, or should I just use the unique ids (primary keys) from the database? If not, how would you create this kind of ids?

like image 240
LuckyLuke Avatar asked Feb 17 '23 17:02

LuckyLuke


1 Answers

If you choose to identify a comment by its sequence number, that is your preference. If in the concept of your application, it makes sense to make the unique identify of a comment it's sequence number when in relation to the post identifier, that is perfectly fine design as long as it is documented.

There is at least two major downfalls to your re-sequencing approach, which may yield your application URI design flawed. The first downfall, is GET methods on a URI should be cacheable, re-sequencing breaks this contract, because item 2 didn't change, but because item 1 did you now change what /2 means. Next, this will obviously break links that people may have created.

I do like the concept of a query param for sequence, however i think it makes sense from my limited understanding of your problem to just use the identifiers simply because the two downfalls I list above are no longer issues.

like image 63
fpmoles Avatar answered Feb 27 '23 05:02

fpmoles