Junior — Middle
Can you explain the differences between HTTP PUT and PATCH methods in the context of REST API?
sobes.tech AI
Answer from AI
The HTTP methods PUT and PATCH are used for updating resources in REST API, but they differ in their semantics and behavior:
-
PUT is an idempotent method that replaces the entire resource on the server with a new representation sent in the request body. If the resource does not exist, it can be created. Repeated requests with the same data will produce the same result.
-
PATCH is used for partial updates of a resource. Only the fields that need to be changed are sent in the request body; the rest remain unchanged. PATCH is not necessarily idempotent, but it can be.
Example:
PUT /users/123
{
"name": "Ivan",
"email": "ivan@example.com"
}
Replaces the entire user 123 resource with a new object with name and email.
PATCH /users/123
{
"email": "newemail@example.com"
}
Updates only the email field, the name remains the same.