Search code examples
restspring-rest

Http "Put" method to update a record and insert new one simultaneously


I have a use case where i need to update an existing record in DB, stamp it as expired, and create a new record with a new expiry date.

For updating the record, I intend to use a "PUT" call. However, for creating a new record, do i need to call a "POST" endpoint again from the UI?

Or can i simply add another repository.save(obj) method in the "PUT" method implementation ?

Thanks..

Edit 1 : The new record is a copy of the expired record, but with a new expiry date.


Solution

  • The main difference between PUT and POST - one is idempotent, the other one isn't. Meaning that you can repeat same PUT many times and this won't be adding more and more entities/elements.

    Usually creating a new resource is a POST operation, because in most situations you send an entity w/o ID, and the server assigns one. So if you repeat the same operation multiple times - you get more entities. This is not idempotent and requires POST.

    So in the perfect world you'd send 2 separate requests: PUT - for expiration, POST - for the new entity. In the real world you may encounter additional constraints:

    • Both operations may need to be run in a single transaction. Otherwise you can remove old entity w/o creating a new one.
    • Separate requests may lead to performance issues or complications on the client side (especially if it's an async environment like JS).

    So you may have to create an ugly API that would accept both entities in 1 request. But such request should be POST because it's not idempotent.

    Though it sounds like the new entity in your situation is just an update to the old entity. This is usually solved by PUTing the same entity with new fields, without sending an explicit removal. In such case server will have to recognize that old entity needs to be marked as expired. And you wouldn't assign a new ID to the updated entity - you'd assign a new version (extra column in DB).