The "idempotent" and the "safe” are two important concepts in HTTP methods used for designing web services and APIs.
With Safe HTTP methods, it’s used for read-only operations when we’re retrieving information from the server without changing anything on the server or it should not modify the state of the server or the resource in any way. Therefore we can cache or prefetch it. Safe HTTP methods include: GET, HEAD, OPTIONS and TRACE.
On the other hand, Idempotent HTTP methods that make the same request multiple times produce the same result as making it once but it does not mean that the server has to respond in the same way on each request. In situations due to network issues, retries, or other factors, Idempotent methods are less likely to lead to unexpected or harmful results when used multiple times. Idempotent HTTP methods include: GET, HEAD, OPTIONS, TRACE, PUT and DELETE.
Let’s talk about PATCH first. The PATCH method is used to partially update a resource on the server. We often use it when we want to only specific fields of an existing resource without affecting the rest of the resource's data. It’s an Idempotent HTTP method which means making the same PATCH request multiple times should have the same effect as making it once. In this project, I use it to update the product field.
How about POST and PUT? Post is used for creating new resources or triggering actions on the server. It’s not Idempotent because making the same POST request multiple times can lead to the creation of multiple resources or multiple actions being taken. With PUT, we also use it to update a resource or create a new one, but when we modify data, it sends the same data in a PUT request multiple times should have the same effect as sending it once.
Notes:
_ When using PUT, to update an existing resource, the request should contain all the data needed to fully update the resource. Any missing data may be interpreted as clearing or nullifying that field.
(not do that)
POST /users
Host: example.com
Content-Type: application/json
{
"name": "New User",
"email": null
}
_ When using PUT to create a new resource, the server should ensure that the provided URI is unique and that it represents the newly created resource.
Example:
POST /users
Host: example.com
Content-Type: application/json
{
"name": "New User",
"email": "[email protected]"
}