๐Ÿ“Œ Spring REST API ์‹ค์Šต - MemoRestController ๊ตฌ์ถ• & Postman ํ…Œ์ŠคํŠธ

My Pale Blue Dotยท2025๋…„ 4์›” 28์ผ
0

SPRING

๋ชฉ๋ก ๋ณด๊ธฐ
22/36
post-thumbnail

๐Ÿ“… ๋‚ ์งœ

2025-04-28


๐Ÿ“ ํ•™์Šต ๋‚ด์šฉ

1๏ธโƒฃ MemoRestController ์„ค๊ณ„

  • ์Šคํ”„๋ง์˜ @RestController๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฉ”๋ชจ ๊ด€๋ฆฌ API ๊ตฌํ˜„.
  • CRUD ์ค‘ ์กฐํšŒ(GET), ๋“ฑ๋ก(POST) ๊ธฐ๋Šฅ ์œ„์ฃผ๋กœ ์‹ค์Šต.

2๏ธโƒฃ ์ฃผ์š” ์ฝ”๋“œ

โœ… ์ „์ฒด ๋ฉ”๋ชจ ์กฐํšŒ

@GetMapping(value = "/getAll", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public List<MemoDto> getAll() {
    log.info("GET /rest/memo/getAll");
    return memoService.getAllMemo();
}
  • URL ํ˜ธ์ถœ: GET http://localhost:8091/ex08_restController/rest/memo/getAll
  • ์‘๋‹ต: JSON ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ ์ „์ฒด ๋ฉ”๋ชจ ๋ฐ˜ํ™˜.

โœ… ๋‹จ๊ฑด ๋ฉ”๋ชจ ์กฐํšŒ (ResponseEntity ํ™œ์šฉ)

@GetMapping(value = "/get/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<MemoDto> get(@PathVariable int id) {
    log.info("GET /memo/get... " + id);
    MemoDto dto = memoService.getMemo(id);

    if (dto == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<>(dto, HttpStatus.OK);
}
  • URL ํ˜ธ์ถœ: GET http://localhost:8091/ex08_restController/rest/memo/get/8889
  • ์ฃผ์˜: DB์— ๊ฐ’์ด ์กด์žฌํ•ด๋„ dto๊ฐ€ null์ด๋ฉด 404 ๋ฐ˜ํ™˜.

โœ… ๋ฉ”๋ชจ ๋“ฑ๋ก (POST + JSON Body)

@PostMapping("/post")
public void add(@RequestBody MemoDto dto) throws SQLException {
    log.info("POST /memo/add_rest_post.." + dto);
    memoService.registraionMemo(dto);
}
  • URL ํ˜ธ์ถœ: POST http://localhost:8091/ex08_restController/rest/memo/post
  • Postman ์„ค์ •:
    • Body โ†’ raw โ†’ JSON
{
  "id": "8890",
  "text": "c",
  "writer": "c",
  "createAt": "2025-04-28T11:34:10"
}

3๏ธโƒฃ Postman ํ…Œ์ŠคํŠธ ์š”์•ฝ

๊ธฐ๋ŠฅMethodURL๋น„๊ณ 
์ „์ฒด ์กฐํšŒGET/rest/memo/getAllJSON ๋ฐฐ์—ด ๋ฐ˜ํ™˜
๋‹จ๊ฑด ์กฐํšŒGET/rest/memo/get/{id}JSON ๋ฐ˜ํ™˜ / 404 ์ฒ˜๋ฆฌ
๋ฉ”๋ชจ ๋“ฑ๋กPOST/rest/memo/postBody์— JSON ์ž…๋ ฅ

4๏ธโƒฃ ๋””๋ฒ„๊น… ํฌ์ธํŠธ

  • ์‘๋‹ต์ด ๋น„์–ด์žˆ๋Š” ๊ฒฝ์šฐ ์ ๊ฒ€์‚ฌํ•ญ
    1. ์„œ๋น„์Šค ๊ณ„์ธต(memoService.getMemo) ๋กœ์ง ํ™•์ธ
    2. DTO ์ง๋ ฌํ™”(Jackson) ์„ค์ • ํ™•์ธ
    3. ์„œ๋ฒ„ ๋กœ๊ทธ & ์˜ˆ์™ธ ๋ฉ”์‹œ์ง€ ํ™•์ธ
    4. Postman ์š”์ฒญ ์„ค์ • (Method, Headers, Body ๋“ฑ)
  • ํ…Œ์ŠคํŠธ์šฉ ๋”๋ฏธ ๋ฐ์ดํ„ฐ ๋ฐ˜ํ™˜์œผ๋กœ ์ง๋ ฌํ™” ์—ฌ๋ถ€ ์ฒดํฌ ๊ถŒ์žฅ.

๐Ÿ”ฅ ์ •๋ฆฌ

  • @RestController์™€ @RequestBody, ResponseEntity๋ฅผ ํ™œ์šฉํ•ด RESTful API ๊ธฐ๋ณธ ๊ตฌํ˜„.
  • Postman์„ ์ด์šฉํ•ด GET/POST ์š”์ฒญ ํ…Œ์ŠคํŠธ ์ˆ˜ํ–‰.
  • ์‘๋‹ต์ด ์—†์„ ๋•Œ๋Š” ์„œ๋น„์Šค ๋กœ์ง, ์ง๋ ฌํ™” ์„ค์ •, ์š”์ฒญ ๋ฐฉ์‹ ๋“ฑ์„ ์ข…ํ•ฉ์ ์œผ๋กœ ์ ๊ฒ€.
  • ์‹ค์Šต์„ ํ†ตํ•ด REST API ํ๋ฆ„๊ณผ ๋””๋ฒ„๊น… ๋ฐฉ๋ฒ•์„ ์ฒด๋“.

๐Ÿ”— ์ฐธ๊ณ  ์ž๋ฃŒ


profile
Here, My Pale Blue.๐ŸŒ

0๊ฐœ์˜ ๋Œ“๊ธ€