Stefan Stefan - 1 month ago 6
reST (reStructuredText) Question

JSON-API design

Lets say I have different kind of objects

House
and
Car
. Now I want to add comments.

Whats better practise?
Having endpoints:

/api/house/:houseId/comments


/api/car/:carId/comments


Or a general api for comments like:

/api/comments/:generalId

Answer

for me product type is implementation detail. To be REST-style I would create API with

/api/product/[productID]

This endpoint would suport GET (get given product),POST (update given product), DELETE

/api/product/

This endpoint would support GET (get all products), PUT (create new product)

/api/product/[productID]/comments/[commentID]

This endpoint would support GET(get given comment for given product) and POST (update given comment), DELETE(delete given comments). In this case, commentID may be unique only per resource, not globally.

/api/product/[productID]/comments

This endpoint will support GET (get all comments for product) and PUT(create new comment), DELETE (delete all comments for product)

api/comments/[commentId]

This resource (with operations GET, POST, DELETE) is also fine. But it needs globaly unique commentId. Feel free to expose such endpoint if you need to manage separate comments without knowing productId. This does not violate REST.

In this API design we have separate resources for each product and comment. We also have resource for all products, and resource for all comments for given product. Each of this resource may support GET,POST,PUT,DELETE. You may ommit some operations (for example do not expose POST on /api/product/[productID]/comments/[commentID] when you do not want to support editing comments.

Edit: as suggested in comments by @lospejos you may use plural forms (products, comments). Either way, your API will be REST-style, with every post/comment being separate resource.

Comments