본문 바로가기

Javascript

[모던 자바스크립트 Deep Dive] 40. REST API

  • REST : HTTP 를 기반으로 클라이언트가 서버의 리소스에 접근하는 방식을 규정한 아키텍처
  • REST API : REST 를 기반으로 서비스 API 를 구현한 것
  • RESTful : REST 의 기본 원칙을 성실히 지킨 서비스 디자인

REST API 의 구성

구성 요소 내용 표현 방법
자원 자원 URL (엔드포인트)
행위 자원에 대한 행위 HTTP 요청 메서드
표현 자원에 대한 행위의 구체적 내용 페이로드

 

REST API 설계 원칙

  • URI 는 리소스를 표현하는데 집중
  • 행위에 대한 정의는 HTTP 요청 메서드를 통해 해야함

1. URI 는 리소스를 표현해야 한다

  • 리소스를 식별할 수 있는 이름은 동사보다는 명사 사용

2. 리소스에 대한 행위는 HTTP 요청 메서드로 표현한다

HTTP 요청 메서드 종류 목적 페이로드
GET index/ retrieve 모든/ 특정 리소스 취득 X
POST create 리소스 생성 O
PUT replace 리소스 전체 교체 O
PATCH modify 리소스의 일부 수정 O
DELETE delete 모든/ 특정 리소스 삭제 X

 

REST API 실습

1. GET 요청

<!DOCTYPE html>
<html>
  <body>
    <h1 id="content"></h1>
  </body>
  <script>
    // XMLHttpRequest 객체 생성
    const xhr = new XMLHttpRequest();

    // XMLHttpRequest 요청 초기화
    xhr.open("GET", "/todos");

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

    xhr.onload = () => {
      if (xhr.status === 200) {
        document.querySelector("#content").textContent = xhr.response;
      }
    };
  </script>
</html>

 

2. POST 요청

<!DOCTYPE html>
<html>
  <body>
    <h1 id="content"></h1>
  </body>
  <script>
    // XMLHttpRequest 객체 생성
    const xhr = new XMLHttpRequest();

    // XMLHttpRequest 요청 초기화
    xhr.open("POST", "/todos");

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

    // HTTP 요청 전송
    xhr.send(JSON.stringify({ id: 4, content: "CODING ⌨️", completed: false }));

    xhr.onload = () => {
      if (xhr.status === 200 || xhr.status === 201) {
        document.querySelector("#content").textContent = xhr.response;
      }
    };
  </script>
</html>

 

3. PUT 요청

<!DOCTYPE html>
<html>
  <body>
    <h1 id="content"></h1>
  </body>
  <script>
    // XMLHttpRequest 객체 생성
    const xhr = new XMLHttpRequest();

    // XMLHttpRequest 요청 초기화
    // todos 리소스에서 id로 todo를 특정하여 id를 제외한 리소스 전체를 교체
    xhr.open("PUT", "/todos/4");

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

    // HTTP 요청 전송
    xhr.send(JSON.stringify({ id: 4, content: "REFACTORING 🔧", completed: false }));

    xhr.onload = () => {
      if (xhr.status === 200 || xhr.status === 201) {
        document.querySelector("#content").textContent = xhr.response;
      }
    };
  </script>
</html>

 

4. PATH 요청

<!DOCTYPE html>
<html>
  <body>
    <h1 id="content"></h1>
  </body>
  <script>
    // XMLHttpRequest 객체 생성
    const xhr = new XMLHttpRequest();

    // XMLHttpRequest 요청 초기화
    // todos 리소스에서 id로 todo를 특정하여 completed만 수정
    xhr.open("PATCH", "/todos/4");

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

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

    xhr.onload = () => {
      if (xhr.status === 200 || xhr.status === 201) {
        document.querySelector("#content").textContent = xhr.response;
      }
    };
  </script>
</html>

 

5. DELETE 요청

<!DOCTYPE html>
<html>
  <body>
    <h1 id="content"></h1>
  </body>
  <script>
    // XMLHttpRequest 객체 생성
    const xhr = new XMLHttpRequest();

    // XMLHttpRequest 요청 초기화
    // todos 리소스에서 id를 사용하여 todo 삭제
    xhr.open("DELETE", "/todos/4");

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

    xhr.onload = () => {
      if (xhr.status === 200 || xhr.status === 201) {
        document.querySelector("#content").textContent = xhr.response;
      }
    };
  </script>
</html>