PUT vs PATCH
기존 자원에 대해 업데이트를 실행하는 API중 PUT과 PATCH의 차이를 알아보자.
PUT | PATCH | |
사용 | 기존 자원에 대한 정보를 업데이트 할 때 | |
자원 일부의 업데이트 정보만 담은 요청을 받을 때 | 넘어오지 않은 정보에 대해 null로 처리 (대상 리소스를 나타내는 데이터를 대체, 전체 교체) |
넘어온 정보에 대해서만 업데이트 진행 (부분 교체) |
URI의 자원이 존재하지 않을 때 | 새로운 자원을 생성하고 정보를 반영 | 자원이 존재하지 않아 오류 발생 |
멱등성 여부 (동일할 요청을 여러번 연속으로 보내도 같은 응답으로 반응) |
O (넘어온 자원이 존재하지 않으면 최초 한번만 생성 후 계속 같은 값을 응답) |
X (자원에 대한 수정이 반복적으로 진행된다.) |
멱등성
PATCH에서 멱등성이 보장되지 않는 다는 것은 무엇일까? 서버에서는 /users와 같은 URI에 대한 PATCHing도 제공한다.
(PUT은 전체 엔티티에 대한 요청을 보냄으로서 멱등성을 보장한다)
// GET /users
[{ "id": 1, "username": "user", "email": "user@email.com" }]
// PATCH /users
[{ "op": "add", "username": "newuser", "email": "newuser@email.com" }]
// GET /users (주어진 정보에 알맞은 새로운 자원이 생성됨)
[{ "id": 1, "username": "user", "email": "user@email.com" },
{ "id": 2, "username": "newuser", "email": "newuser@email.com" }]
// PATCH /users (동일한 요청을 다시 보냄)
[{ "op": "add", "username": "newuser", "email": "newuser@email.com" }]
// GET /users (동일한 자원이 추가되는 것을 확인할 수 있음)
[{ "id": 1, "username": "user", "email": "user@email.com" },
{ "id": 2, "username": "newuser", "email": "newuser@email.com" },
{ "id": 3, "username": "newuser", "email": "newuser@email.com" }]
위와 같은 결과는 우리가 원하는 결과가 아닐 것이다.
PATCH를 멱등성을 보장하는 방식으로 사용하기 위해서는 다음과 같이 자원을 명시하여 요청을 보내주도록 한다.
// GET /users/1
{
"username": "user",
"email": "user@email.com"
}
// PATCH /users/1 (이메일 정보 변경 요청)
{
"email": "newemail@email.com"
}
// GET /users/1 (이메일 정보 변경 된 것 확인)
{
"username": "user",
"email": "newemail@email.com"
}
// PATCH /users/1 (다시 요청)
{
"email": "newemail@email.com"
}
// GET /users/1 (동일하게 유지됨 (멱등성 반영))
{
"username": "user",
"email": "newemail@email.com"
}
(추가)
요즘에는 url로 id를 받아 조회 후 값을 변경하는 방식으로 모든 데이터를 조회하고 업데이트 진행하므로 put을 사용하는 경우가 많다.
Use of PUT vs PATCH methods in REST API real life scenarios
First of all, some definitions: PUT is defined in Section 9.6 RFC 2616: The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an a...
stackoverflow.com
Use of PUT vs PATCH methods in REST API real life scenarios
First of all, some definitions: PUT is defined in Section 9.6 RFC 2616: The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an a...
stackoverflow.com
https://stackoverflow.com/questions/29186613/http-patch-is-idempotent-or-non-idempotent
HTTP PATCH is idempotent or non idempotent?
I have read lots of places that HTTP Patch is non-idempotent. Can someone explain me why it is non-idempotent ? Because as per the definition - Idempotent methods may or may not change the resource
stackoverflow.com
[ 기술 스터디 ] PUT과 PATCH 차이
PUT과 PATCH 사이. 미묘한 무언가가 있다.
velog.io