Home > OS >  Post or Put should be used - if the object exists to be updated otherwise new to be created?
Post or Put should be used - if the object exists to be updated otherwise new to be created?

Time:10-11

I have a method which receive object and check in the database if it exist. If the answer is yes, the value is updated, otherwise new record is inserted in the database. Which should be used - PUT or POST, because in one case I'm updating the record and in the other new one is created ?

CodePudding user response:

This behavior is what we usually call "upserts", basically insert an item if it doesn't exists else update the item. Reference

As for which http verb you could use:

The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), whereas successive identical POST requests may have additional effects, akin to placing an order several times. Reference

Having that said, the upsert operation has different effects depending on the situation, so I would say a POST request is more appropriate because if the record already exists it will return a 200 OK indicating the record was updated, if it doesn't exists it will return a 201 CREATED indicated that a new record was inserted.

But this is not written in stone, I've seen people follow different approaches like:

  1. if the user has control over what properties are going to be used to identify whether the record already exists, then the upsert endpoint might be a PUT
  2. if the system has the autonomy to dictate which of the properties will be used to determine if the record already exists, then the upsert endpoint it might be a POST

Example for item #1 would be PUT /resource/identifier, the system would get the identifier and look into the database to see if it already exists and if so it completely updates the record, if it doesn't exists it inserts a new record tagging it with the supplied identifier.

Example for item #2 would be POST /resource, the user don't care which properties will be used to determine the existence of the record, it trusts that the right operation will be performed regardless of what he sent.

  • Related