简体   繁体   中英

REST: Why expose POST and PUT endpoint of API when both can be done with just any one of these endpoints?

We are creating an ecommerce website where several sellers would push their products through an API exposed. Each seller has its own unique identifier for each product (product_id + seller_id) that they send with each request. Hence, they do not rely on "product id" generated by our system to send PUT request after POST.

For each of our client we have to tell to send POST only for already not created stocks, PUT only for already created stocks. Clients need to keep log of all already created stocks and based on that decide which API to hit. On API side too, we send validation error if we get POST for already existing stock OR PUT for non-existing stock.

I want to understand why do we have to keep this complexity on client and server when things could have been simplified if we choose just one of these request that would CREATE/UPDATE according to the situation.

For example if choose only POST. We will create product if request comes and it does not exist OR update it if it is already present.

Why REST suggests to keep POST/PUT separately?

There is a semantic difference in PUT and POST. First consider the URI you execute the requests against:

POST /products

This adds a new product. The resulting product ID is not yet known and will be generated when it is added to the database. Posting the same product twice will result in two exactly same entries in the catalog. This may be intentional behavior in a REST API. (Maybe not in your case though.)

PUT /products/235647

This updates an existing product. The id is known to the client and this ensures that only that resource is updated. A POST against the URI does not make little sense.

When you want to add further data to the element, you would use a more specific URI:

POST /products/235647/reviews

And then update that data:

PUT /products/235647/reviews/2

Separating the Create and Update verbs ensures that duplicates are created intentionally and not by mistake. Also the URIs are significantly different and thus you need different handlers anyway.

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