Search code examples
restapirestful-architectureapi-design

Rest API design: How to create restful API for POSTing resource with multiple sub-resources?


We are an e-commerce website and want to create API to give an interface to all our clients to send Product related info via this API. We currently need 3 types of Product info:

  • basicDetails: like price, color etc.
  • images: images of the product
  • reviews: reviews of that product

Approach1: Allow the clients to send all information through single API.

/api/product/
{
    "basicDetails" : {}, //json with all basic details of the product.
    "images": {}, //json containing array of images of the product.
    "reviews": {} //json containing array of reviews of the product.
}

Approach2: Create different API for all sub-resources.

/api/product/basicdetails/
/api/product/images/
/api/product/reviews/

Approach3: Create different API for all sub-resources with hierarchical URI.

/api/productBasicDetails/
/api/productImages/
/api/productReviews/

Which is recommended restful approach?


Solution

  • If images and reviews are both integral part of a product and product mustn't exist without these beings I'd go for approach 1 since in 3 you're defining lots of endpoints that users will probably find unclear how to use them.

    Otherwise, approach 2 seems the best and is also the clearest one. Let your clients create the product with all the basic details. In response to that POST request a 201 Created should be sent along with Location header that contains an URL which points to the newly created resource. Then to edit the product itself, send a request directly /api/product/{id}/. To update/delete/create subresources (namely image or a review) send appropriate request to /api/product/{id}/images/ or /api/product/{id}/reviews/ respectively. This way you'll have clean separation of concerns along with easy-to-understand and consistent API. In case of any further resources are added you're operating still in the single root endpoint area instead of multiple (as in approach 3).

    Also, the disadvantage of approach 1 is that the body might difficult to construct for the clients - e.g. optional images - will there null value be sent or no key at all?