PUT or PATCH, which one should I use in this scenario

Asked

Viewed 25 times

3

I have a hypothetical database:

CREATE TABLE person (
    code integer NOT NULL,
    name varchar(50) NOT NULL,
    PRIMARY KEY (code)
);

When I perform a POST, I create by sending on the body:

{
    "code": 15,
    "name": "John"
}

As you can see, the code is a primary key, meaning I can’t create more than one line with the same code.

When I make a PUT (endpoint/person/{code}) I send the same body of the post, however, I will not update the code, only the name. When the code is sent different from the one sent in endpoint, I just ignore what comes in the body and consider what comes in endpoint.

My question is, this way I do can be considered a PUT, or I should use PATCH ?

1 answer

2


The difference between PUT and PATCH is merely semantic. That is, the meaning of the request: its purpose.

An interesting feature of the PUT method is that it updates an existing record, but creates a new non-existent case. That is, when sending the "code" and "name" through a PUT request, but the "code" does not yet exist in the database, it will be created. Therefore, it would not make much sense for you to inform the "code" via URL.

But what would be the difference between PUT and POST?

The idempotency. While in the POST method making numerous identical requests in a row would create numerous records, in the PUT method only one would be created. The first request would create the record and all subsequent requests would only update the existing record with the same data - that is, it would not be changed.

In your case, if the idea is to inform the "code" via URL just to update it, PATCH makes more sense. But one premise of PATCH is that it can make partial changes to the record, considering structures with more than one column. Doesn’t seem to be your case.

In short:

  • Use the PATCH if:

    • Enter "code" via URL;
    • If "code" does not exist, it will give error;
    • partial updates of the resource are permitted;
  • Use the PUT if:

    • Enter the "code" via the request body;
    • If "code" does not exist, it will be created;
    • Partial updates of the resource are not allowed;

Detail: the methods are not unique to each other, you can very well implement both and get the most out of your API.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.