REST API – What Should PUT Do with Complex Objects?

apicdtorestweb

Let's suppose I have the following objects in my domain:

class Warehouse
{
    int Id;
    string Address;
    Item[] Inventory;
}

class Item
{
    int Id;
    string Name;
    int Price;
    int WarehouseId;
}

I have a collection of all the warehouses and all the items. I am using a web api to provide access to them in REST style. So, when I retrieve a warehouse, I get something like this:

{
    "Id": 1,
    "Address": "123, 1st street",
    "Inventory":
    [
        { "Id" : "1", "Name": "LED TV", "Price" : "1300", "WarehouseId" : "1" },
        { "Id" : "2", "Name": "Console", "Price" : "500", "WarehouseId" : "1" },
    ]
}

What should be the result of making a PUT request to the warehouse endpoint?

Obviously, it should override the address with the provided one. But should it also override the inventory?

What if it contains a new item, not present in the collection of items? Should it create it?

What if it does not contain one of the items present before? Should it delete it?

Best Answer

I would separate the warehouse from the items:

GET api/warehouse 
Gets a list of warehouses

PUT api/warehouse/{warehouseid} 
Updates some meta information on that warehouse (address etc)

GET api/warehouse/{warehouseid}/inventory 
Gets the inventory of the warehouse (you can supply some search parameters to narrow

GET api/warehouse/warehouseid}/inventory/{itemid} 
Gets a particular item, details, how many in warehouse, etc.

DELETE api/warehouse/warehouseid}/inventory/{itemid} 
Delete a particular item from that inventory or at least decrements the qty that is stored in the warehouse by one.

And so forth.

Related Topic