반응형

1. REST(REpresentational State Transfer)

: Network Resource(자원)를 정의하고 처리하는 방법을 설명하는 일련의 원칙을 기반으로 하는 Architecture Style

☞ Client와 Server가 Data를 주고받는 방식에 대해 정리한 원칙이 있고 그 원칙을 기반으로하는 Architecture Style을 REST라고 한다.

☞ HTTP의 장점을 최대한 활용할 수 있는 Architecture로 REST의 원칙은 HTTP를 잘 활용하기 위한 원칙으로 볼 수 있다.

 

REpresentational(표현)  State(상태)  Transfer(전달)

자원(Resource)의 표현을 이용해 상태(정보) 전달

                 HTTP URI                                        HTTP Method

 

2. RESTful

: REST라는 Architecture Style의 제약조건을 모두 만족하는 System은 RESTful하다고 말할 수 있다.

 

3. URI 구조

: Collection과 Document의 조합으로 구성되며 동사를 사용하지 않는다.

  • Collection : Table 전체
    ☞ 일반적으로 객체들의 집합이므로 복수 명사 사용
  • Document : 행 하나 (객체)
    ☞ 집합 중 객체를 구분할 수 있는 값
더보기

/cources/front

/cources/back

/cources/front/crews/jjyoung

 

 

4. HTTP Method

: REST API에서 Resource(자원)에 대한 행위를 표현하기 위해 사용된다.

CRUD(데이터 처리 방법) HTTP Method
Create POST
Read GET
Update PUT / PATCH
Delete DELETE

 

4.1. Read(조회) - GET

<!-- 해당 Collection에 대한 전체 정보 -->
GET /cources
<!-- Document의 정보 조회 -->
GET /cources/front

 

4.2. Create(생성) - POST

<!-- backend coach 집합에 jjyoung라는 닉네임을 가진 코치 개체 생성 -->

POST /courses/back/coaches
<!-- body에 생성할 내용을 담음 -->
body {nickname: jjyoung}

 

4.3. Update(수정) - PUT

<!-- frontend coach 집합 중 첫 번째 코치 닉네임을 jjyoung로 수정 -->

PUT /courses/front/coaches
<!-- 수정할 내용을 body에 담음 -->
body {id: 1, nickname: jjyoung}

 

4.4. Delete(삭제) - DELETE

<!-- frontend crew 집합 중 jjyoung 삭제 -->
DELETE /courses/front/crews/jjyoung

 

5. REST Arichtecture의 제약 조건

5.1. Client - Server

: Client가 Server에게 Request를 보내고 Server가 Client에게 Response를 보내는 구조로 Server와 Client의 역할이 분리되어있다.

  • Server : API 제공과 제공된 API를 이용해 비즈니스 로직을 처리하거나 저장
  • Client : 사용자 인증이나 컨텍스트(세션, 로그인 정보) 등을 관리

 

5.2. Stateless(무상태성)

: Client와 Server의 통신에는 상태가 없어야하며 모든 요청은 필요한 정보를 담고 있어야 한다.

☞ Client가 두 가지 요청을 보냈을 때 두 번째 요청 시 Server는 Client의 첫 번째 요청의 내용을 모르므로 두 번째 요청시에도 필요한 모든 정보를 담고 있어야 한다.

 

5.3. Cache

: 일반적인 서비스에서 60 ~ 80% 가량의 Transaction이 Select와 같은 조회성 트랜잭션이며 GET은 얼마든지 호출해도 매번 같은 결과를 만들어내므로(Idempotent) 캐싱이 가능하다.

 

5.4. Uniform Interface

 

5.4.1. Identification of Resources
: 자원은 유일하게 식별 가능해야하며 Resource가 하나 이상의 유일한 특정 주소인 URI로 식별되어야 한다.
☞ 아직 POST Method로만 Request를 보내기 때문에 URI나 Request Body로 어떤 동작을 할 지 알려줘야 한다.

 

5.4.2. Manipulation of Resources through Representation
: HTTP Method로 표현(CRUD)을 담아야 한다.
☞ 안전한 Operation과 안전하지 않은 Operation 간의 강한 분리를 제공해야 한다.

HTTP Method Idempotent Safe
GET O O
HEAD O O
PUT O X
POST X X
DELETE O X
PATCH X X
더보기

Idempotent : 같은 요청을 여러 번 하더라도 그 결과가 동일함
Safe : 자원을 변경하지 않음

 

5.4.3. Self-Descriptive Messages
: Message를 스스로를 설명해야한다.

☞ 요청 작업 완료 및 응답 이해가 가능하도록 충분한 정보들을 HTTP Method, Status Code, Header 등을 활용해 전달해야 한다.

더보기

HTTP Status Code

: 발생한 에러의 종류를 Communication하기 위해 상태 코드 사용

Level 200 (Success) Level 400 Level 500
200 : OK 400 : Bad Request 500: Internal Server Error
201 : Created 401 : Unauthorized 501: Not Implemented
203 : Non - Autheoritative 403 : Forbidden 502 : Bad Gateway
204 : No Content 404 : Not Found 503 : Service Unavailable
  409 : Conflict 504 : Gateway Timeout
    599 : Network Timeout

 

5.4.4. Hypermedia As the Engine Of Application State(HATEOAS)

: Hyperlink를 통해 Application의 상태가 전이되어야 한다.

☞ HTTP Response에 다음 Action이나 관계되는 Resource에 대한 HTTP Link를 함께 Return한다.

☞ 장점 : 요청 URI가 변경되더라도 Client는 Server에서 동적으로 생성된 URI를 사용함으로써 Client는 URI 수정에 따른 코드를 변경하지 않아도 된다.

 

5.5. Layered System

: 계층으로 구성이 가능해야 한다.

☞ Server는 다중 계층으로 구성될 수 있으나 Client 입장에서는 계층에 상관 없이 Server만 호출하면 된다.

e.g., 순수 비즈니스 로직을 수행하는 Server, 사용자 인증, 암호화(SSL), 로드 밸런싱 등을 하는 계층을 추가하거나 PROXY, 게이트웨이 같은 중간 매체 사용 가능

 

5.6. Code-On-Demand(Option)

: Server가 Network를 통해 Client에 Program을 전달하면 그 Program이 Client에서 실행될 수 있어야 한다.

e.g., JavaScript를 사용해 Server에서 Program 전달하면 Client에서 동적으로 실행 가능하다.

 

6. Richardson Maturity Model

Glory of REST
Level 3 : Hypermedia Controls
Level 2 : HTTP Verbs
Level 1 : Resources
Level 0 : The Swamp of POX

 

6.1. Level 0 : The Swamp of POX

: POX(Plain Old XML)를 주고받는 단순한 RPC Style System

☞ HTTP를 RPC 기반의 원격 통신을 위한 터널링 Mechanism으로 사용된다.

충족된 제약 조건 : Server-Client, Stateless, Layered System, Manipulation of Resources through Representation

RPC(Remote Procedure Call, 원격 프로시저 호출)
: 별도의 원격 제어를 위한 코딩 없이 다른 주소 공간에서 함수나 프로시저를 실행할 수 있게 하는 프로세스 간 통신 기술 (= Client가 Server에 있는 Program을 실행하기 위해 사용하는 통신 기술)
☞ RPC를 이용하면 개발자는 실행 Program이 로컬 위치에 있든 원격 위치에 있든 동일한 코드를 이용할 수 있다.
☞ Client가 Server에게 Message를 보내 Program을 실행시키고 Server에서는 그 Program의 결과를 Client에게 전송

예제

더보기

1. Client - 2022년 3월 19일 회의실 1의 예약되지 않은 시간대를 알아내는 요청

POST /appointmentService HTTP/1.1
[various other headers]

<openSlotRequest date = "2022-03-19", mittingroom = "1"/>

 

2. Server - 2022년 3월 19일 회의실 1의 예약되지 않은 시간대를 알려주는 응답

HTTP/1.1 200 OK
[various other headers]

<openSlotList>
    <slot start = "1600", end = "1700">
        <meetingroom = "1"/>
    </slot>
    
    <slot start = "1900", end = "2100">
        <meetingroom = "1"/>
    </slot>
</openSlotList>

 

3. Client - 19시 ~ 21시 회의실을 예약하는 요청

POST /appointmentService HTTP/1.1
[various other headers]

<appointmentRequest>
    <slot meetingroom = "1", start = "1900", end = "2100"/>
    <bookingperson = "졍"/>
</appointmentRequest>

 

4.1. Server - 예약 성공

HTTP/1.1 200 OK
[various other headers]

<appointment>
    <slot meeingroom = "1", start = "1900", end = "2100"/>
    <bookingperson = "졍"/>
</appointment>

 

4.2. Server - 예약 실패

HTTP/1.1 200 OK
[various other headers]

<appointmentRequestFailure>
    <slot meetingroom = "1", start = "1900", end = "2100"/>
    <bookingperson = "졍"/>
    <reason> Slot Not Available </reson>
</appointmentRequestFailure>

 

6.2. Level 1 : Resources

: Resource를 도입해 모든 요청을 단일 서비스 End Point로 보내는 것이 아니라 개별 Resource(meetingroom, slot 등)와 통신한다.

☞ Level 0에서는 모든 요청이 appointmentService라는 단일 서비스 End Point로 보내졌다.

충족된 제약 조건 : Identification of Resources

예제

더보기

1. Client - 2022년 3월 19일 회의실 1의 예약되지 않은 시간대를 알아내는 요청

POST /meetingrooms/1 HTTP/1.1
[various other headers]

<openSlotRequest date = "2022-03-19"/>

 

2. Server - 2022년 3월 19일 회의실 1의 예약되지 않은 시간대를 알려주는 응답

HTTP/1.1 200 OK
[various other headers]

<openSlotList>
    <!-- Slot id를 이용해 resource 만듦 -->
    <slot id = "1234", meetingroom = "1", start = "1600", end = "1700"/>
    <slot id = "5678", meetingroom = "1", start = "1900", end = "2100"/>
</openSlotList>

 

3. Client - 19시 ~ 21시에 회의실 1을 예약하는 요청

POST /slots/5678 HTTP/1.1
[various other headers]

<appointmentRequest>
    <bookingperson = "졍"/>
</appointmentRequest>

 

4. Server - 예약 완료

HTTP/1.1 200 OK
[various other headers]

<appointment>
    <slot id = "5678", meetingroom = "1", start = "1900", end = "2100"/>
    <bookingperson = "졍"/>
</appointment>

 

6.3. Level 2 : HTTP Method

: HTTP Method를 사용할 수 있으며 Level 0, 1에 비해 HTTP의 사용법에 가능한 가깝게 사용한다.

충족된 제약 조건 : Manipulation of Resources through Representation, Self-Descriptive Messages, Cache

예제

더보기

1. Client - 2022년 3월 19일 회의실 1의 예약되지 않은 시간대를 알아내는 요청

 GET /meetingrooms/1/slots?date=20220319&status=open HTTP/1.1
 HOST : https://techcourse.woowahan.com/

 

2. Server - 2022년 3월 19일 회의실 1의 예약되지 않은 시간대를 알려주는 응답

HTTP/1.1 200 OK
[various other headers]

<openSlotList>
    <slot id = "1234", meetingroom = "1", start = "1600", end = "1700"/>
    <slot id = "5678", meetingroom = "1", start = "1900", end = "2100"/>
</openSlotList>

 

3. Client - 19시 ~ 21시에 회의실 1을 예약하는 요청

POST /slots/5678 HTTP/1.1
[various other headers]

<appointmentRequest>
    <bookingperson = "졍"/>
</appointmentRequest>

 

4.1. Server - 예약 완료

HTTP/1.1 201 Created
Location : slots/5678/appointment
[various other headers]

<appointment>
    <slot id = "5678", meetingroom = "1", start = "1900", end = "2100"/>
    <bookingperson = "졍"/>
</appointment>

 

4.2. Server - 예약 실패

HTTP/1.1 409 Conflict
[various other headers]

<openSlotList>
    <slot id = "5678", meetingroom = "1", start = "1900", end = "2100"/>
    <bookingperson = "졍"/>
</openSlotList>

 

6.4. Level 3 : Hypermdedia Controls

: HATEOAS를 도입해 Client가 Server로부터 어떤 요청을 할 때, 요청에 필요한 URI를 응답에 포함시켜 반환한다.

☞ Client가 전적으로 Server와 동적인 상호작용이 가능하다.

충족된 제약 조건 : HATEOAS

예제

더보기

1. Client - 2022년 3월 19일 회의실 1의 예약되지 않은 시간대를 알아내는 요청

 GET /meetingrooms/1/slots?date=20220319&status=open HTTP/1.1
 HOST : https://techcourse.woowahan.com/

 

2. Server - 2022년 3월 19일 회의실 1의 예약되지 않은 시간대를 알려주는 응답

HTTP/1.1 200 OK
[various othe headers]

<openSlotList>
    <slot id = "1234", meetingroom = "1", start = "1600", end = "1700">
        <link rel = "linkrels/slot/book", uri = "slots/1234"/>
    </slot>
    
    <slot id = "5678", meetingroom = "1", start = "1900", end = "2100">
        <link rel = "linkrels/slot/book", uri = "slots/5678"/>
    </slot>
</openSlotList>

 

3. Client - 19시 ~ 21시에 회의실 1을 예약하는 요청

POST /slots/5678 HTTP/1.1
[various other headers]

<appointmentRequest>
    <bookingperson = "졍"/>
</appointmentRequest>

 

4. Server - 예약 완료

HTTP/1.1 201 Created
Location : https://techcourse.woowahan.com/slots/5678/appointment
[various other heads]

<appointment>
    <slot id = "5678", meetingroom = "1", start = "1900", end = "2100"/>
    <bookingperson = "졍"/>
    <link rel = "/linkrels/appointment/cancel", uri = "/slots/5678/appointment"/>
    <link rel = "self", uri = /slots/5678/appointment"/>
    ...
    <link rel = "/linkrels/help", uri = "/help/appointment"/>
</appointment>

 

7. 결론

  • REST는 Software Architecture의 한 형식이다.
  • REST Architecture는 여러 개의 제약 조건을 가지고 있다.
  • REST Architecture의 제약 조건을 모두 만족하는 System을 RESTful한 System이라고 한다.
  • HTTP Method, Status Code를 용도에 맞게 써야하고, HTTP HeaderLink를 신경쓰면 RESTful한 Service를 설계할 수 있다.

 

참고

https://youtu.be/xY7cpMuWh4w

https://youtu.be/NODVCBmyaXs

반응형

'CS기술 지식 > 네트워크' 카테고리의 다른 글

[네트워크] Physical Layer(물리 계층)란?  (0) 2022.03.23
[네트워크] OSI 7계층이란?  (0) 2022.03.20
[네트워크] TCP vs UDP  (0) 2022.03.09
[네트워크] GET, POST 방식  (0) 2022.03.06

+ Recent posts