기록방

[10일차] 10장 : REST API와 JSON 본문

FrameWork/스프링

[10일차] 10장 : REST API와 JSON

Soom_1n 2024. 6. 23. 05:39

길벗 IT도서에서 주관하는 코딩 자율학습단 8기 : Spring Boot 파트에 참여한 기록입니다 [ 목록 ]

10.1 REST API와 JSON의 등장 배경

  • REST API(Repersentational State Transfer API)
    • 서버의 자원을 클라이언트에 구애받지 않고 사용할 수 있게 하는 설계 방식
    • HTTP 요청에 대한 응답으로 서버의 자원을 반환
    • 서버에서 보내는 응답이 특정 기기에 종속되지 않도록 모든 기기에서 통용될 수 있는 데이터를 반환
    • 화면(view)이 아닌 데이터(data)를 전송
    • 응답 데이터는 JSON(JavaScript Object Notation)을 사용

 

 

  • JSON 데이터는 키(key)와 값(value)으로 구성된 정렬되지 않은 속성(property)의 집합
    • 키는 문자열이므로 항상 큰따옴표(””)로 감싸고, 값은 문자열인 경우에만 큰따옴표(””)로 감쌈
{
	"name" : "망고",
	"breeds" : "골든리트리버",
	"age" : 2
}

 

10.2 REST API 동작 살펴보기

10.2.1 {JSON} Placeholder 사이트 둘러보기

 

  • 사용 방법 : 아래 Run script 실행

 

  • 제공하는 자원

 

  • HTTP 메서드와 URL 경로

 

  • Guide의 CRUD 예시 확인하기
    • fetch의 메서드가 기본적으로 GET이라 생략 가능
    • PUT : 기존 데이터를 전부 새 내용으로 변경. 기존 데이터가 없다면 새로 생성
    • PATCH : 기존 데이터 중에서 일부만 새 내용으로 변경

10.2.2 Talend API Tester 설치하기

10.2.3 GET 요청하고 응답받기

  • 전체 데이터 조회
    • GET https://jsonplaceholder.typicode.com/posts

 

  • 단일 데이터 조회
    • GET https://jsonplaceholder.typicode.com/posts/1

 

  • 데이터 조회 실패하기
    • GET https://jsonplaceholder.typicode.com/posts/101

 

  • HTTP 상태 코드
    1. 1XX(정보) : 요청이 수신 돼 처리 중입니다.
    2. 2XX(성공) : 요청이 정상적으로 처리됐습니다.
    3. 3XX(리다이렉션 메시지) : 요청을 완료하려면추가 행동이 필요합니다.
    4. 4XX(클라이언트 요청 오류) : 클라이언트의 요청이 잘못돼 서버가 요청을 수행할 수 없습니다.
    5. 5XX(서버 응답 오류) : 서버 내부에 에러가 발생해 클라이언트 요청에 대해 적절히 수행하지 못했습니다.

 

  • HTTP 요청 메시지와 응답 메시지
GET /posts/101 HTTP/1.1
Host: jsonplaceholder.typicode.com

HTTP/1.1 404
date: Sat, 22 Jun 2024 18:16:49 GMT
content-type: application/json; charset=utf-8
content-length: 2
report-to: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1719080209&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=HnPGSEDlBIwkN1kG64JmXpfrmp%2BDUr0Qmby9olZiOGw%3D"}]}
reporting-endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1719080209&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=HnPGSEDlBIwkN1kG64JmXpfrmp%2BDUr0Qmby9olZiOGw%3D
nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]}
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1719080263
vary: Origin, Accept-Encoding
access-control-allow-credentials: true
cache-control: max-age=43200
pragma: no-cache
expires: -1
x-content-type-options: nosniff
etag: W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"
via: 1.1 vegur
cf-cache-status: EXPIRED
priority: u=1,i
server: cloudflare
cf-ray: 897e3b490b8f7d8f-LAX
alt-svc: h3=":443"; ma=86400
{}
  • HTTP 메시지는 시작 라인(start line), 헤더(header), 빈 라인(blank line), 본문(body)으로 구성
    • 시작 라인 : HTTP 요청 또는 응답 내용. 항상 한 줄
    • 헤더 : HTTP 전송에 필요한 부가 정보(metadata)
    • 빈 라인 : 헤더의 끝을 알리는 빈 줄로, 헤더가 모두 전송되었음을 알림
    • 본문 : 실제 전송하는 데이터

 

  • 시작 라인과 헤더
GET /posts/101 HTTP/1.1
Host: jsonplaceholder.typicode.com
  • 시작 라인 : 요청의 종류(GET), URL 경로(/post/101), 사용하는 HTTP 버전(HTTP/1.1)
  • 헤더 : 호스트 주소

 

  • 응답 메시지
HTTP/1.1 404
date: Sat, 22 Jun 2024 18:16:49 GMT
content-type: application/json; charset=utf-8
content-length: 2
report-to: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1719080209&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=HnPGSEDlBIwkN1kG64JmXpfrmp%2BDUr0Qmby9olZiOGw%3D"}]}
reporting-endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1719080209&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=HnPGSEDlBIwkN1kG64JmXpfrmp%2BDUr0Qmby9olZiOGw%3D
nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]}
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1719080263
vary: Origin, Accept-Encoding
access-control-allow-credentials: true
cache-control: max-age=43200
pragma: no-cache
expires: -1
x-content-type-options: nosniff
etag: W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"
via: 1.1 vegur
cf-cache-status: EXPIRED
priority: u=1,i
server: cloudflare
cf-ray: 897e3b490b8f7d8f-LAX
alt-svc: h3=":443"; ma=86400

{}
  • 응답 메시지 시작 라인 : HTTP 버전(HTTP/1.1), 상태 코드(404)
  • 응답 메시지 헤더 : 응답 날짜(date), 응답 데이터 형식(content-type)
  • 응답 메시지 헤더 아래 한 줄 띄고 본문 : 404 에러 나서 본문은 비어 있음({})

10.2.4 POST 요청하고 응답받기

  • 데이터 생성하기
POST https://jsonplaceholder.typicode.com/posts

{
  "title" : "오늘은 왠지",
  "body" : "치킨을 먹고 싶어라!"
}

POST /posts HTTP/1.1
Content-Length: 76
Content-Type: application/json
Host: jsonplaceholder.typicode.com

{
  "title" : "오늘은 왠지",
  "body" : "치킨을 먹고 싶어라!"
}

HTTP/1.1 201
date: Sat, 22 Jun 2024 18:30:07 GMT
content-type: application/json; charset=utf-8
content-length: 87
location: https://jsonplaceholder.typicode.com/posts/101
report-to: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1719081007&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=QBPzItjkS8LtDZUMzB4YDOHZ1O1hzzIlmDD2l8cmYEg%3D"}]}
reporting-endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1719081007&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=QBPzItjkS8LtDZUMzB4YDOHZ1O1hzzIlmDD2l8cmYEg%3D
nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]}
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1719081043
vary: Origin, X-HTTP-Method-Override, Accept-Encoding
access-control-allow-credentials: true
cache-control: no-cache
pragma: no-cache
expires: -1
access-control-expose-headers: Location
x-content-type-options: nosniff
etag: W/"57-vctLgHSa5/ZEW3s79veQsfkMIuM"
via: 1.1 vegur
cf-cache-status: DYNAMIC
priority: u=1,i
server: cloudflare
cf-ray: 897e4ec4eed5520e-LAX
alt-svc: h3=":443"; ma=86400

{
  "title": "오늘은 왠지",
  "body": "치킨을 먹고 싶어라!",
  "id": 101
}

 

  • JSON 형식이 틀린 데이터 생성하기 : json key에 큰따옴표 빠짐
POST https://jsonplaceholder.typicode.com/posts

{
  title : "오늘은 왠지",
  body : "치킨을 먹고 싶어라!"
}

POST /posts HTTP/1.1
Content-Length: 72
Content-Type: application/json
Host: jsonplaceholder.typicode.com

{
  title : "오늘은 왠지",
  body : "치킨을 먹고 싶어라!"
}

HTTP/1.1 500
date: Sat, 22 Jun 2024 18:33:34 GMT
content-type: text/html; charset=utf-8
report-to: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1719081214&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=H25wVwsSKYzaOgIUoYEtlXUUf56R0ANDBU%2BYoz2uYKg%3D"}]}
reporting-endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1719081214&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=H25wVwsSKYzaOgIUoYEtlXUUf56R0ANDBU%2BYoz2uYKg%3D
nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]}
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1719081223
vary: Origin, X-HTTP-Method-Override, Accept-Encoding
access-control-allow-credentials: true
cache-control: no-cache
pragma: no-cache
expires: -1
via: 1.1 vegur
cf-cache-status: DYNAMIC
priority: u=1,i
server: cloudflare
cf-ray: 897e53d80ca92a8c-LAX
alt-svc: h3=":443"; ma=86400

SyntaxError: Unexpected token t in JSON at position 4
    at JSON.parse (<anonymous>)
    at parse (/app/node_modules/body-parser/lib/types/json.js:89:19)
    at /app/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/app/node_modules/body-parser/node_modules/raw-body/index.js:224:16)
    at done (/app/node_modules/body-parser/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/app/node_modules/body-parser/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1358:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

 

10.2.5 PATCH 요청하고 응답받기

  • 데이터 수정하기
PATCH https://jsonplaceholder.typicode.com/posts/1

{
  "title" : "abcdef",
  "body" : "123456"
}

 

10.2.6 DELETE 요청하고 응답받기

  • 데이터 삭제하기
DELETE https://jsonplaceholder.typicode.com/posts/10

DELETE /posts/10 HTTP/1.1
Host: jsonplaceholder.typicode.com

HTTP/1.1 200
date: Sat, 22 Jun 2024 18:37:19 GMT
content-type: application/json; charset=utf-8
content-length: 2
report-to: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1719081439&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=hvRTNVeqMKpIOp%2BRa4uRX3nEuARlNC2ncwOlr3n26uc%3D"}]}
reporting-endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1719081439&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=hvRTNVeqMKpIOp%2BRa4uRX3nEuARlNC2ncwOlr3n26uc%3D
nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]}
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1719081463
vary: Origin, Accept-Encoding
access-control-allow-credentials: true
cache-control: no-cache
pragma: no-cache
expires: -1
x-content-type-options: nosniff
etag: W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"
via: 1.1 vegur
cf-cache-status: DYNAMIC
priority: u=1,i
server: cloudflare
cf-ray: 897e5951aa9a6a2b-LAX
alt-svc: h3=":443"; ma=86400

{}

 

🚀 1분 퀴즈

  1. 다음 빈칸에 들어갈 HTTP 응답 코드 번호 대를 골라 쓰세요.
    • ( 4XX ) : 클라이언트의 요청이 잘못돼 서버가 요청을 수행할 수 없다.
    • ( 2XX ) : 요청이 정상적으로 처리됐다.
    • ( 5XX ) : 서버 내부에 에러가 발생해 클라이언트의 요청에 대한 적절한 수행을 하는 데 실패했다.
    • ( 3XX ) : 요청을 완료하려 추가 행동이 필요하다.
    • ( 1XX ) : 요청이 수신 돼 처리 중이다.

✅ 셀프 체크

  • id가 10번인 사용자의 오늘 할 일(todos)을 생성, 조회, 수정, 삭제하는 HTTP 요청 메시지를 작성하세요.
    • 오늘 할 일(todos)의 json 데이터는 다음과 같이 구성
      • userId(사용자 아이디)
      • id(오늘 할 일 아이디)
      • title(오늘 할 일 제목)
      • completed(완료 여부)
    • 사용자 아이디는 1~10번까지 있음
    • 각 userId(사용자 아이디)당 id(오늘 할 일 아이디)는 20개씩 배정, id 번호는 이어서 관리
      • userId 1번의 id : 1~20
      • userId 2번의 id : 21~40
      • userId 3번의 id : 41~60
      • userId 10번의 id : 181~200

1. 오늘 할 일 생성 : 10번 사용자의 오늘 할 일을 생성하되, title은 “맛집 탐방하기”로 설정하세요.

POST /todos HTTP/1.1
Content-Length: 77
Content-Type: application/json
Host: jsonplaceholder.typicode.com

{
  "userId" : 10,
  "title" : "맛집 탐방하기",
  "completed" : false
}

 

2. 오늘 할 일 조회 : 10번 사용자의 오늘 할 일 전체를 조회하세요.

GET /users/10/todos HTTP/1.1
Host: jsonplaceholder.typicode.com

HTTP/1.1 200
date: Sat, 22 Jun 2024 18:58:02 GMT
content-type: application/json; charset=utf-8
report-to: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1719082682&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=fvjhJ0OP3e5yE9sL65r2TFFifsZyGJ7Z%2BvLo8aUCPBU%3D"}]}
reporting-endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1719082682&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=fvjhJ0OP3e5yE9sL65r2TFFifsZyGJ7Z%2BvLo8aUCPBU%3D
nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]}
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1719082723
vary: Origin, Accept-Encoding
access-control-allow-credentials: true
cache-control: max-age=43200
pragma: no-cache
expires: -1
x-content-type-options: nosniff
etag: W/"94b-Xf3KAbsgAZYN4iY133g5Nn+yLLE"
content-encoding: gzip
via: 1.1 vegur
cf-cache-status: MISS
priority: u=1,i
server: cloudflare
cf-ray: 897e77ad4a922ab3-LAX
alt-svc: h3=":443"; ma=86400
[
  {
    "userId": 10,
    "id": 181,
    "title": "ut cupiditate sequi aliquam fuga maiores",
    "completed": false
  },
  {
    "userId": 10,
    "id": 182,
    "title": "inventore saepe cumque et aut illum enim",
    "completed": true
  },
// ~~~~~~
  {
    "userId": 10,
    "id": 199,
    "title": "numquam repellendus a magnam",
    "completed": true
  },
  {
    "userId": 10,
    "id": 200,
    "title": "ipsam aperiam voluptates qui",
    "completed": false
  }
]

 

3. 오늘 할 일 수정 : 10번 사용자의 오늘 할 일 중 id 200번의 title을 “멋지게 숨쉬기”로 수정하세요.

PATCH /todos/200 HTTP/1.1
Content-Length: 76
Content-Type: application/json
Host: jsonplaceholder.typicode.com

{
  "userId" : 10,
  "title" : "멋지게 숨쉬기",
  "completed" : true
}

HTTP/1.1 200
date: Sat, 22 Jun 2024 18:59:52 GMT
content-type: application/json; charset=utf-8
report-to: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1719082792&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=ZkiHYL1e4jG3gJHPxYR7M9D%2FF%2Fe6rZCSYr4gxPsNYLc%3D"}]}
reporting-endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1719082792&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=ZkiHYL1e4jG3gJHPxYR7M9D%2FF%2Fe6rZCSYr4gxPsNYLc%3D
nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]}
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1719082843
vary: Origin, Accept-Encoding
access-control-allow-credentials: true
cache-control: no-cache
pragma: no-cache
expires: -1
x-content-type-options: nosniff
etag: W/"56-4LNDg0YeE/XjFgpASDin9gse2sc"
via: 1.1 vegur
cf-cache-status: DYNAMIC
priority: u=1,i
server: cloudflare
cf-ray: 897e7a5b3ccc7bfb-LAX
content-encoding: zstd
alt-svc: h3=":443"; ma=86400

{
  "userId": 10,
  "id": 200,
  "title": "멋지게 숨쉬기",
  "completed": true
}

 

4. 오늘 할 일 삭제 : 10번 사용자의 오늘 할 일 중 id 200번 데이터를 삭제하세요.

DELETE /todos/200 HTTP/1.1
Host: jsonplaceholder.typicode.com

HTTP/1.1 200
date: Sat, 22 Jun 2024 19:00:44 GMT
content-type: application/json; charset=utf-8
content-length: 2
report-to: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1719082844&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=e53dH1CXx7BeBWPMV4xzTEVzNtC4We4ZoowIwwBMQJ4%3D"}]}
reporting-endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1719082844&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=e53dH1CXx7BeBWPMV4xzTEVzNtC4We4ZoowIwwBMQJ4%3D
nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]}
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1719082903
vary: Origin, Accept-Encoding
access-control-allow-credentials: true
cache-control: no-cache
pragma: no-cache
expires: -1
x-content-type-options: nosniff
etag: W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"
via: 1.1 vegur
cf-cache-status: DYNAMIC
priority: u=1,i
server: cloudflare
cf-ray: 897e7ba39f66840a-LAX
alt-svc: h3=":443"; ma=86400

{}

 

🏓 더 알아볼 내용

1. REST API란

REST API는 Representational State Transfer의 약자로, 분산 네트워크 상에서 자원(리소스)을 표현하고 그 상태를 전송하는 아키텍처 스타일입니다. REST API의 특징은 아래와 같습니다.

  • 자원(Resources)
    • REST에서는 모든 자원을 고유한 식별자(URI)를 통해 표현합니다. 웹의 자원은 각각의 URI로 식별되며(예: /tasks , /books , /users), 이러한 자원은 서버에 의해 관리됩니다.
  • 표현(Representation)
    • 자원의 상태는 다양한 표현으로 나타낼 수 있습니다. 주로 JSON 또는 XML
      형식의 데이터를 사용하여 자원의 표현을 전송합니다. 클라이언트는 이러한 표현을 통해 서버와 상호 작용합니다.
  • 상태 전이(Stateless)
    • REST는 상태를 유지하지 않는(stateless) 특징을 가지고 있습니다. 각 요청은 모든 필요한 정보를 포함하고 있어야 하며, 서버는 요청을 처리하기 위해 필요한 정보 만을 이용합니다. 세션 상태는 서버에 저장되지 않고 클라이언트에 의해 유지되어야 합니다.
  • 인터페이스 일관성(Uniform Interface)
    • REST는 일관된 인터페이스를 제공합니다. 자원에 대한 표준화된 인터페이스로서, CRUD(Create, Read, Update, Delete) 연산을 통해 자원을 조작합니다. 이로써 서버와 클라이언트 간의 상호 운용성을 높입니다.

위의 4가지 특징(혹은 self-descriptive, HATEOAS)을 엄격하게 지키는 API를 보고 RESTful API라고 합니다.

1) 자원 식별

REST API의 좋은 예와 나쁜 예

API 좋은 예 나쁜 예
글 조회 GET /post/{id} GET /get/posts/{id}
글 생성 POST /posts POST /posts/create
글삭제 DELETE /posts/{id} DELETE /posts/delete/{id}

위 표의 나쁜 예를 보면 이미 HTTP 메서드로 자원에 대한 행동(GET, POST, DELETE)을 정의했음에도 불구하고 URI로 또 한 번 행동을 나타냅니다. 이는 적절하지 않습니다.

2) 표현

REST API는 데이터를 JSON 형식으로 표시합니다.

{
    "postId": 1,
    "title": "RESTful API",
    "content": "RESTful API에 대한 간단한 설명입니다.",
    "author": "John"
}

3) 상태 전이

REST API는 서버가 클라이언트의 상태를 저장하지 않습니다. HTTP 메서드를 통해 클라이언트와 서버 간의 상태 전이를 일으켜 통신을 효과적으로 할 수 있도록 합니다.

4) 인터페이스 일관성

REST API는 일관된 인터페이스를 제공하기 위해 HTTP 메서드와 URI를 일관성 있게 사용합니다. 예를 들어 게시물을 생성하기 위해서는 POST /posts를 사용하며, 게시물을 업데이트하기 위해서는 PUT /posts/{postId}를 사용합니다. 만약 POST /posts/create나 PUT /posts/update/{postId}로 쓴다면 올바르지 않겠죠.

2. HTTP 메서드

REST에서 자원에 대한 행위는 HTTP 메서드를 통해서 나타낸다고 했습니다. 그렇기 때문에 HTTP 메서드는 매우 중요합니다.

HTTP 메서드에는 총 9개의 메서드가 존재합니다.

  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • CONNECT
  • OPTIONS
  • TRACE
  • PATCH

이중에서 주로 사용되는 메서드는 다음의 5가지입니다.

  • GET, POST, PUT, DELETE, PATCH

특히 PUT과 PATCH의 차이는 면접에서도 단골 질문으로 나오니 꼭 알아두세요.

  • PUT : 데이터 전체를 수정
  • PATCH : 데이터의 일부만 수정

또 하나 짚고 싶은 메서드는 HEAD입니다. HEAD는 GET과 같지만 ResponseBody, 즉 응답 데이터가 없습니다. 그럼 대체 왜 필요한 걸까요? HEAD는 GET과 다르게 응답 데이터가 없기 때문에 가볍고 전송이 빠릅니다. 그래서 주로 서버의 상태를 확인하는 용도로도 쓰이곤 합니다.

@RequestMapping("/")
@RestController
@RequiredArgsConstructor
public class Test {
    @RequestMapping(value = "/ping", method = RequestMethod.HEAD)
    public void ping() {
    }
}

서버가 정상적으로 동작 중일 경우 http://localhost:8080/ping에 HEAD 요청을 보낸다면 아무런 응답 없이 200을 응답합니다. 만약 서버가 죽었거나 올바르게 동작하지 않는다면 200을 응답하지 않겠죠(500번대 에러 혹은 타임아웃 혹은 실패). 이런 용도로 사용이 가능한 재미있는 메서드입니다.

728x90