Spring Boot

Spring Boot API Server 개발에서 GET / POST / PUT / DELETE 요청 처리하는 방법

Pro.Dev 2025. 1. 8. 13:14
반응형

Spring Boot API Server 개발에서 GET / POST / PUT / DELETE 요청 처리하는 방법

Spring Boot는 RESTful 웹 서비스를 쉽게 개발할 수 있도록 다양한 HTTP 요청 메서드(GET, POST, PUT, DELETE 등)를 처리하는 기능을 제공합니다. 이 글에서는 각 요청 메서드를 처리하는 방법과 코드 예제를 소개합니다.


1. HTTP 요청 메서드란?

  • GET: 데이터를 조회할 때 사용됩니다.
  • POST: 새로운 데이터를 생성할 때 사용됩니다.
  • PUT: 기존 데이터를 수정할 때 사용됩니다.
  • DELETE: 데이터를 삭제할 때 사용됩니다.

Spring Boot에서는 이러한 메서드를 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping 어노테이션으로 쉽게 처리할 수 있습니다.


2. GET 요청 처리

예제: 데이터 조회 API

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    @GetMapping("/api/items")
    public String getItems() {
        return "모든 아이템을 조회합니다.";
    }

    @GetMapping("/api/items/{id}")
    public String getItemById(@PathVariable int id) {
        return "ID가 " + id + "인 아이템을 조회합니다.";
    }
}

설명:

  • /api/items: 모든 아이템 데이터를 반환합니다.
  • /api/items/{id}: 특정 ID에 해당하는 데이터를 반환합니다.

3. POST 요청 처리

예제: 새로운 데이터 생성 API

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    @PostMapping("/api/items")
    public String createItem(@RequestBody String itemData) {
        return "다음 데이터를 생성했습니다: " + itemData;
    }
}

설명:

  • @RequestBody를 사용해 클라이언트에서 전송한 JSON 데이터를 Java 객체로 변환합니다.
  • 응답으로 생성된 데이터를 반환합니다.

4. PUT 요청 처리

예제: 기존 데이터 수정 API

import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    @PutMapping("/api/items/{id}")
    public String updateItem(@PathVariable int id, @RequestBody String itemData) {
        return "ID가 " + id + "인 아이템을 다음 데이터로 수정했습니다: " + itemData;
    }
}

설명:

  • @PathVariable을 사용해 URL 경로에서 ID 값을 가져옵니다.
  • 수정할 데이터를 @RequestBody로 받아 처리합니다.

5. DELETE 요청 처리

예제: 데이터 삭제 API

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    @DeleteMapping("/api/items/{id}")
    public String deleteItem(@PathVariable int id) {
        return "ID가 " + id + "인 아이템을 삭제했습니다.";
    }
}

설명:

  • 삭제할 데이터의 ID를 URL 경로로 전달받아 처리합니다.

6. 통합 코드 예제

하나의 컨트롤러에서 모든 요청 메서드를 처리하는 예제입니다:

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/items")
public class ApiController {

    private Map<Integer, String> items = new HashMap<>();

    @GetMapping
    public Map<Integer, String> getAllItems() {
        return items;
    }

    @GetMapping("/{id}")
    public String getItemById(@PathVariable int id) {
        return items.getOrDefault(id, "아이템이 존재하지 않습니다.");
    }

    @PostMapping
    public String createItem(@RequestBody String itemData) {
        int id = items.size() + 1;
        items.put(id, itemData);
        return "아이템이 생성되었습니다: ID = " + id;
    }

    @PutMapping("/{id}")
    public String updateItem(@PathVariable int id, @RequestBody String itemData) {
        if (items.containsKey(id)) {
            items.put(id, itemData);
            return "아이템이 수정되었습니다: ID = " + id;
        } else {
            return "아이템이 존재하지 않습니다.";
        }
    }

    @DeleteMapping("/{id}")
    public String deleteItem(@PathVariable int id) {
        if (items.containsKey(id)) {
            items.remove(id);
            return "아이템이 삭제되었습니다: ID = " + id;
        } else {
            return "아이템이 존재하지 않습니다.";
        }
    }
}

반응형