ZeroBase/CS

HTTP 메서드 PUT, PATCH 차이

Red_Horse 2025. 7. 29. 00:07
항목 PUT PATCH
의미 전체 업데이트 부분 업데이트
요청 시 데이터 전체 데이터 수정하고자 하는 일부 데이터
동작 리소스를 완전히 대체 리소스의 일부만 변경
리소스가 없을 때 새로 생성 일반적으로 에러 발생 (PATCH는 리소스가 존재해야 함)
멱등성 O (같은 요청 여러 번 해도 결과 동일) △ (일반적으로는 멱등성을 유지하려고 설계)
예시 데이터(User)

 

 
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

 

PUT  – 전체 데이터 업데이트

 
PUT /api/users/1
Content-Type: application/json

{
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com"
}
[HttpPut("{id}")]
public IActionResult UpdateUser(int id, [FromBody] User updatedUser)
{
    var user = _context.Users.FirstOrDefault(u => u.Id == id);
    if (user == null)
    {
        // 새로 생성할 수도 있음
        _context.Users.Add(updatedUser);
    }
    else
    {
        // 전체 덮어쓰기
        user.Name = updatedUser.Name;
        user.Email = updatedUser.Email;
    }

    _context.SaveChanges();
    return Ok(user);
}
 

 

PATCH – 일부 데이터만 업데이트

 
PATCH /api/users/1
Content-Type: application/json

{
    "email": "alice@newdomain.com"
}
[HttpPatch("{id}")]
public IActionResult PatchUser(int id, [FromBody] JsonElement updates)
{
    var user = _context.Users.FirstOrDefault(u => u.Id == id);
    if (user == null) return NotFound();

    if (updates.TryGetProperty("email", out var emailProp))
    {
        user.Email = emailProp.GetString();
    }

    // 다른 필드들도 조건적으로 업데이트 가능
    _context.SaveChanges();
    return Ok(user);
}
 
  • PUT은 리소스를 통째로 바꾸거나 새로 생성
  • PATCH는 리소스의 일부만 수정

'ZeroBase > CS' 카테고리의 다른 글

대규모 트래픽으로 인한 서버 과부화 해결방법  (0) 2025.07.31
네트워크 장치  (1) 2025.07.30
HTTP메서드 GET, POST 차이  (1) 2025.07.28
토큰 기반 로그인 방식  (0) 2025.07.26
세션기반 인증 방식  (0) 2025.07.25