简体   繁体   中英

Should I use PUT or POST to add a new subitem to an existing item?

Suppose I have an item (model) which has fields that are arrays, for example:

const item = {
  name: "",
  prices: [{somePriceSpecificObject}],
}

When I want to add a new price to that item prices array, which method is better to be used (in terms of quality I guess), PUT or POST?

Right now I am using PUT because by creating a new price for prices array I am editing the item , but I am now making functionality that will let me edit the existing entries, and it naturally goes into PUT aswell, which got me thinking about this issue.

Because, it also kinda makes sense to use POST , because price relative to the item is a new thing, but the item relative to me with the new price is still the item, just with an edited field (prices).

Now one solution to my dilemma might be to make a separate model for prices ? But I never did that, because, a given item in my specific conditions, will never have more than a handful of prices, and it will make me make more queries to the database (I am not concerned about performance, but still, just looking for best practices).

So which route do you think I should go?

EDIT: My api endpoints look like this at the moment:

post("/one", POST.oneItem);
put("/addprice", PUT.addPriceToItem);

put("/editone/:id", PUT.EDIT.item);
put("/editone/:id/price/:priceId", PUT.EDIT.price);

Notice I had to make a nested EDIT object in my PUT object (that provides the handling functions), to be able to easily distinguish between adding a price and editing a price, so that got me into thinking about all of that.

I have seen in most cases of production code there is never a delete query being run as the schema has a soft delete key which gets turned when wanting to delete a particular row/document. Hence it is always using PUT as a best practice even for delete. Any changes to an existing document need to be a PUT because it will help you in improving performance unless the document is completely different from the one before. It even becomes easier while caching as one needs to update the cache and not add another one in and remove some other one (in case the cache becomes full at that point). In the end, if you intend to keep prices as an array then I guess PUT is a better choice.

"PUT /uri" creates/updates the thing at "/uri". Your example where the URI contains "/addprice" is IMHO a misuse of PUT.

If you have a collection X and want to add an item Y, use "PUT /X/Y". If you want the server to name the item, use "POST /x".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM