[JS Deep Dive] REST API

David Oh·2022년 11월 25일
0

JS Deep Dive

목록 보기
2/6

REST

representational state transfer

  • 로이 필딩에 의해 처음 소개된 개념
  • 웹이 HTTP를 사용하지 못하는 상황을 보고 HTTP의 장점을 최대한 활용할 수 있는 아키텍처
    • HTTP를 기반으로 클라이언트가 서버의 리소스에 접근하는 방식을 규정한 아키텍처

REST API 구성

REST는 자체 표현 구조로 구성되어 REST API만으로 HTTP 요청의 내용을 이해 가능

  1. 자원 : 자원 / URI(엔드포인트)
  2. 행위 : 자원에 대한 행위 / HTTP 요청 메서드
  3. 표현 : 자원에 대한 행위의 구체적인 내용 / 페이로드

REST API 설계 원칙

  1. URI는 리소스를 표현하는데 집중

    • 리소스를 식별할 수 있는 이름은 동사보다는 명사를 사용
    GET / todos / 1
  2. 행위에 대한 정의는 HTTP 요청 메서드를 통해 해야함

    • HTTP 요청 메서드는 클라이언트가 서버에게 요청의 종류와 목적을 알리는 방법이다.
    • 주로 5가지 요청 메서드를 사용하여 CRUD를 구현
      HTTP 요청 메서드종류목적페이로드
      GETindex / retrieve모든/ 특정 리소스 취득X
      POSTcreate리소스 생성O
      PUTreplace리소스의 전체 교체O
      PATCHmodify리소스의 일부 수정O
      DELETEdelete모든 / 특정 리소스 삭제X
    • 리소스에 대한 행위는 HTTP 요청 메서드를 통해 표현하며 URI에 표현하지 않는다.
    DELETE / todos / 1

    JSON Server를 이용한 REST API 실습

    요청을 전송하고 응답을 받기 위해서는 서버가 필요합니다.

    GET 요청

    <!DOCTYPE html>
    <html">
    <body>
      <pre></pre>
      <script>
        const xhr = new XMLHttpRequest()
        // HTTP 요청 초기화
        // todos 리소스에서 모든 todo 를 취득
        xhr.open("GET", "/todos")
        // HTTP 요청 전송
        xhr.send()
        // load 이벤트는 요청이 성공적으로 완료된 경우 발생
        xhr.onload = () => {
          if (xhr.status === 200){
            document.querySelector('pre').textContent = xhr.response
          } else {
            console.error('Error', xhr.status, xhr.statusText)
          }
        }
      </script>  
    </body>
    </html>
    • todos 리소스에서 id를 사용하여 특정 todo를 취득합니다.
    <!DOCTYPE html>
    <html">
    <body>
      <pre></pre>
      <script>
        const xhr = new XMLHttpRequest()
        // HTTP 요청 초기화
        // todos 리소스에서 id를 사용하여 특정 todo를 취득
        xhr.open("GET", "/todos/1")
        // HTTP 요청 전송
        xhr.send()
        // load 이벤트는 요청이 성공적으로 완료된 경우 발생
        xhr.onload = () => {
          if (xhr.status === 200){
            document.querySelector('pre').textContent = xhr.response
          } else {
            console.error('Error', xhr.status, xhr.statusText)
          }
        }
      </script>  
    </body>
    </html>

POST 요청

todos 리소스에 새로운 todo를 생성합니다.

POST 요청 시에는 setRequesetHeader 메서드를 사용하여 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정해야 합니다.

  • payload
    사용에 있어서 전송되는 데이터를 뜻한다.
    페이로드는 전송의 근본적인 목적이 되는 데이터의 일부분으로 그 데이터와 함께 전송되는 헤더와 메타데이터와 같은 데이터는 제외한다.
    <!DOCTYPE html>
    <html">
    <body>
      <pre></pre>
      <script>
        const xhr = new XMLHttpRequest()
        // HTTP 요청 초기화
        // todos 리소스에서 새로운 todo를 생성
        xhr.open("POST", "/todos")
    
        // 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정
        xhr.setRequestHeader('content-type', 'application/json')
    
        // HTTP 요청 전송
        // 새로운 todo를 생성하기 위해 페이로드를 서버에 전송해야 한다.
        xhr.send(JSON.stringify({ id: 4, content: 'Angular', completed: false}))
    
        // load 이벤트는 요청이 성공적으로 완료된 경우 발생
        xhr.onload = () => {
          if (xhr.status === 200 || xhr.status === 201){
            document.querySelector('pre').textContent = xhr.response
          } else {
            console.error('Error', xhr.status, xhr.statusText)
          }
        }
      </script>  
    </body>
    </html>

PUT 요청

특정 리소스 전체를 교체할 때 사용합니다.

PUT 요청 시에는 setRequestHeader 메서드를 사용하여 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정해야 합니다.

```
<!DOCTYPE html>
<html">
<body>
  <pre></pre>
  <script>
    const xhr = new XMLHttpRequest()
    // HTTP 요청 초기화
    // todos 리소스에서 id로 todo를 특정하여 id를 제외한 리소스 전체를 교체
    xhr.open("PUT", "/todos/4")

    // 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정
    xhr.setRequestHeader('content-type', 'application/json')

    // HTTP 요청 전송
    // 리소스 전체를 교체하기 위해 페이로드를 서버에 전송해야 한다.
    xhr.send(JSON.stringify({ id: 4, content: 'React', completed: true}))

    // load 이벤트는 요청이 성공적으로 완료된 경우 발생
    xhr.onload = () => {
      if (xhr.status === 200){
        document.querySelector('pre').textContent = xhr.response
      } else {
        console.error('Error', xhr.status, xhr.statusText)
      }
    }
  </script>  
</body>
</html>
```

PATCH 요청

특정 리소스의 일부를 수정할 때 사용합니다.

해당 PATCH 요청 역시도, setRequestHeader 메서드를 사용하여 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정해야 합니다.

```
<!DOCTYPE html>
<html>
  <body>
    <pre></pre>
    <script>
      const xhr = new XMLHttpRequest();
      // HTTP 요청 초기화
      // todos 리소스에서 id로 todo를 특정하여 id를 제외한 리소스 전체를 교체
      xhr.open("PATCH", "/todos/4");

      // 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정
      xhr.setRequestHeader("content-type", "application/json");

      // HTTP 요청 전송
      // 리소스를 수정하기 위해 페이로드를 서버에 전송해야 한다.
      xhr.send(JSON.stringify({ completed: false }));

      // load 이벤트는 요청이 성공적으로 완료된 경우 발생
      xhr.onload = () => {
        if (xhr.status === 200) {
          document.querySelector("pre").textContent = xhr.response;
        } else {
          console.error("Error", xhr.status, xhr.statusText);
        }
      };
    </script>
  </body>
</html>
```

DELETE 요청

todos 리소스에서 id를 이용하여 todo를 삭제합니다.

```
<!DOCTYPE html>
<html>
  <body>
    <pre></pre>
    <script>
      const xhr = new XMLHttpRequest();
      // HTTP 요청 초기화
      // todos 리소스에서 id로 todo를 특정하여 리소스를 삭제
      xhr.open("DELETE", "/todos/4");

      // HTTP 요청 전송
      xhr.send();

      // load 이벤트는 요청이 성공적으로 완료된 경우 발생
      xhr.onload = () => {
        if (xhr.status === 200) {
          document.querySelector("pre").textContent = xhr.response;
        } else {
          console.error("Error", xhr.status, xhr.statusText);
        }
      };
    </script>
  </body>
</html>
```
profile
let David_Oh === UX+Programming

0개의 댓글