REST: Why expose POST and PUT an API endpoint when both can only execute from one of those endpoints?

We are creating an e-commerce website where multiple sellers will promote their products through an open API. Each seller has their own unique ID for each product (product_id + seller_id), which they submit with each request. Hence, they do not rely on the "product ID" generated by our system to send a PUT request after a POST.

For each of our clients, we have to tell to send POST only for not already created shares, PUT only for already created shares. Clients should keep a log of all shares already created and based on this they will decide which API to hit. On the API side, we also send a validation error if we receive a POST for an existing stock or a PUT for a non-existent stock.

I want to understand why we have to keep this complexity on the client and server when things could be simplified if we only select one of these queries, which would be CREATE / UPDATE as appropriate.

For example, if you select only POST. We will create a product if a request comes in and it doesn't exist OR update it if it already exists.

Why does REST suggest keeping POST / PUT separate?

+3


source to share


1 answer


There is a semantic difference in PUT and POST. First, let's look at the URI with which you make requests:

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. Submitting the same product again will result in two identical catalog entries. This may be intentional behavior in the REST API. (Maybe not in your case.)

PUT /products/235647

      

This updates an existing product. The identifier is known to the client and this ensures that only this resource is updated. POST against URI doesn't make any sense.



If you want to add additional data to an element, you must use a more specific URI:

POST /products/235647/reviews

      

And then update this data:

PUT /products/235647/reviews/2

      

Separating verbs Create

and Update

ensuring that duplicates are created intentionally and not by mistake. Also, the URIs differ significantly from each other, and you need different handlers anyway.

+2


source







All Articles