Home > Blockchain >  Restful API Response: Nesting Objects vs Adding new fields
Restful API Response: Nesting Objects vs Adding new fields

Time:11-20

Let's say we have a ProductType table in our database. This represents types of products that can exist:

productTypeId name description capacity pricePerNight
1 Tent This is a tent 4 20

Let's say we have a Product table in our database. This represents actual physical Products that exist (i.e. in a rental shop's inventory):

id productTypeId (FK) condition lastUsed
6 1 good 18/11/21
7 1 bad 18/11/21
8 1 medium 18/11/21

Now let's say I was making a public API which allows clients to query all available products and the price of those products for a specific set of dates.

My options are: (a) Return an edited version of the ProductType object with new fields (e.g. quantityAvailable and priceForDates) conveying the extra information requested:

{
        "productTypeId": 1,
        "name": "Tent",
        "description": "This is a tent",
        "capacity": 4,
        "quantityAvailable": 1,
        "priceForDates": 60,
}

(b) Wrap the ProductType object in a parent object then add extra fields (e.g. quantityAvailable and priceForDates) to the parent object:

{
         "quantityAvailable": 3,
         "priceForDates": 60,
         "product":
                   {
                      "productTypeId": 1,
                      "name": "Tent",
                      "description": "This is a tent",
                      "capacity": 4,
                   }

}

I am confronted by this situation quite regularly and I'm wondering what best practice is for a RESTful API. Any opinions very welcome.

EDIT: IRL I am building a public API which needs to be as intuitive and easy to use as possible for our company's integrating partners.

CodePudding user response:

This is borderline opinion-based but still, this is my take on this.

I would go with option (b). The reason is that you might be exposing your Product as the following in other endpoints:

"product": {
   "productId": 1,
   "name": "Tent",
   "description": "This is a tent",
   "capacity": 4,
}

In this case, it is important to be consistent and to represent Product with the same structure in all your endpoints.

On top of this, this seems the response to the call of checking the availability of a product for a given period of days. Even the way you phrased it "(...) allows clients to query all available products and the price of those products for a specific set of dates." shows that the price and the number of available products are just additional information about a given Product. Hence, they should be included alongside Product but not as part of Product. For example priceForDates is clearly not a Product property.

  • Related