Home > Back-end >  Should I use PATCH or POST to create and update a resource at the same time?
Should I use PATCH or POST to create and update a resource at the same time?

Time:10-28

I know that PATCH should update the existing resource and POST should create a new resource. However, my current endpoint has to update and create at the same time.

For example: a Buyer pays the Seller money for an item purchase, so the balance of their account should change, and a new payment transaction should also be created.

I am thinking of returning the Transaction object in the response body. Which method should I use?

CodePudding user response:

Typically PUT is the correct method for both creation and updating.

POST should be used if the client can't determine the target URI, but if the client can determine the target URI, PUT is the best method.

For example, PUT /article/hello-world should return 201 created if this article didn't exist yet, and 204/200 if it did and it got replaced.

However, I have some reservations for your exact case. In your example, it sounds like:

  • You are creating a new transaction
  • This should affect balances of existing accounts

It's also most likely that the client doesn't decide what the target URI will be.

In that case, I would mainly just think of this operation from the perspective of the transaction. If you want to communicate that a transaction had an effect on other resources, you might want to use a Link header for this.

Examples

Request

POST /transactions HTTP/1.1
Content-Type: application/json

{
  "from": "/accounts/123",
  "to": "/accounts/456",
  "quantity": "55.00"
}

Response:

HTTP/1.1 201 Created
Location: /transactions/555513412
Link: </account/123>; rel="invalidates"
Link: </account/456>; rel="invalidates"

Note that the 'invalidates' link relationship has a draft status, but it's a great idea and I've used it many times in our APIs

  • Related