0

One post can have many comments.

How can I design REST API urls for HTTP POST and HTTP PATCH for comments. My idea is to have the following endpoints:

HTTP GET: /posts/{postId}/comments
HTTP GET (all comments): /comments
HTTP POST: /posts/{postId}/comments
HTTP PATCH: /comments/{commentId}

Are these urls correct? Because I thought also about:

HTTP PATCH: /posts/{postId}/comments/{commentId}

But here a user needs to know also {postId} to edit a comment so:

HTTP PATCH: /comments/{commentId}

looks better, I think. What do you think?

1
  • how exactly do you see a partial update of a comment to work?
    – Ewan
    Commented Feb 26 at 16:19

1 Answer 1

3

REST doesn't care what spelling conventions you use for your resource identifiers.

HTTP expects that, to patch a resource, the PATCH request will target the same resource identifier as a GET request. (This is a consequence of how caching works, see RFC 9111.)

So if you are fetching the current representation of a "comments resource" via

GET /comments/1

The you (RFC 2119) SHOULD be sending patches to the representation of that resource via

PATCH /comments/1

so that general purpose caches can understand the semantics of what is going on, and do intelligent things.


An important idea in REST is the uniform interface constraint; among other things, it implies that everyone should understand the semantics of requests and responses the same way -- no one resource should be a "special case" that assumes different meaning to the messages.

It follows that "nested resources" should understand request messages the same way that everything else does; GET means GET, PATCH means PATCH, and so on.


As for the design of your resource identifiers, the machines don't care (that's part of the point of "uniform" interface), so choose spelling conventions that best meet the needs of the human beings you value.

1
  • OK, thank you, so I will do: HTTP GET (get post comments): /posts/{postId}/comments || HTTP GET (get all comments): /comments || HTTP GET (get single comment): /comments/{commentId} || HTTP POST: /posts/{postId}/comments || HTTP PATCH: /comments/{commentId} Commented Feb 26 at 15:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.