반응형

 내용은 이웅모 님의 "모던 자바스크립트 DeepDive" 책을 보고 정리한 내용입니다. 저작권 보호를 위해 책의 내용은 요약되었습니다.

 

REST API

  • REST API는 웹 서비스 간에 데이터를 주고받을 수 있는 소프트웨어 인터페이스를 말한다.

REST API의 구성

표 1) REST API의 구성

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

REST API 설계 원칙

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

  • URI는 리소스를 표현해야한다. 리소스를 식별하는 이름은 동사보다는 명사를 사용한다. 이름에 get 같은 표현이 들어가면 안된다.

예시 1)

//bad
GET /getTodos/1

// good
GET /todos/1

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

  • 리소스에 대한 행위는 HTTP 요청 메서드를 통해 표현하며 URI에 표현하지 않는다.

예시 2)

// bad
GET /todos/delete/1

// good
DELETE /todos/1

JSON Server를 이용한 Rest API 실습

예시 3) 임시 DB로 사용할 db.json 파일

{
  "todos": [
    {
      "id": 1,
      "name": "sjmoon",
      "alive": true
    },
    {
      "id": 2,
      "content": "sslee",
      "alive": false
    },
    {
      "id": 3,
      "name": "tony",
      "alive": true
    },
    {
      "id": 4,
      "name": "hysong",
      "alive": true
    }
  ]
}

1. GET 요청

예시 4) get 요청으로 todos 리소스에서 모든 todo를 획득

<!DOCTYPE html>
<!DOCTYPE html>
<html>
    <body>
        <pre></pre>
        <script>
            const xhr = new XMLHttpRequest();
            // HTTP 요청 초기화
             // todos 리소스에서 모든 toto 취득(index)
            xhr.open('GET', '/todos');

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

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

 
결과

[
  {
    "id": 1,
    "name": "sjmoon",
    "alive": true
  },
  {
    "id": 2,
    "content": "sslee",
    "alive": false
  },
  {
    "id": 3,
    "name": "tony",
    "alive": true
  }
]

 
예시 5) get 요청으로 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 = () => {
                // status 값이 200(OK)이면 정상 응답
                if(xhr.status === 200) {
                    document.querySelector('pre').textContent = xhr.response;
                }else{
                    console.error('Error', xhr.status, xhr.statusText);
                }
            };
        </script>
    </body>
</html>

 
결과

{
  "id": 1,
  "name": "sjmoon",
  "alive": true
}

2. POST 요청

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

예시 6) post 요청하여 id가 4인 정보 추가

<!DOCTYPE html>
<html>
    <body>
        <pre></pre>
        <script>
            const xhr = new XMLHttpRequest();
            // HTTP 요청 초기화
            // todos 리소스에 새로운 todo 생성
            xhr.open('POST', '/todos');

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

            // HTTP 요청 전송
            xhr.send(JSON.stringify({id:4, name: "jjmoon", alive: true}));

            // load 이벤트는 요청이 성공적으로 완료된 경우 발생
            xhr.onload = () => {
                // status 값이 200(OK) 이거나 202(Created)이면 정상 응답
                if(xhr.status === 200 || xhr.status === 201) {
                    document.querySelector('pre').textContent = xhr.response;
                }else{
                    console.error('Error', xhr.status, xhr.statusText);
                }
            };
        </script>
    </body>
</html>

 
결과

{
  "id": 4,
  "name": "jjmoon",
  "alive": true
}

3. PUT 요청

  • PUT 은 특정 리소스 전체를 교체할 때 사용한다.
  • id로 특정 todo를 찾아 id를 제외한 리소스 전체를 교체한다.
  • setRequestHeader 메서드를 사용하여 요청 몸체에 담아 서버로 전송할 페이로드 MIME 타입을 지정해야 한다.

예시 7) PUT 요청으로 id가 4인 todo를 교체

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

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

            // HTTP 요청 전송
            xhr.send(JSON.stringify({id:4, name: "hysong", alive: false}));

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

 
결과

{
  "id": 4,
  "name": "hysong",
  "alive": false
}

4. PATCH 요청

  • PUT 은 특정 리소스 일부분을 수정할 때 사용한다
  • id로 특정 todo를 찾아 id를 제외한 리소스 일부를 수정한다.
  • setRequestHeader 메서드를 사용하여 요청 몸체에 담아 서버로 전송할 페이로드 MIME 타입을 지정해야 한다.

예시 8) PATCH 요청으로 id가 4인 todo의 alive를 true로 변경한다.

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

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

            // HTTP 요청 전송
            xhr.send(JSON.stringify({alive: true}));

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


결과

{
  "id": 4,
  "name": "hysong",
  "alive": true
}

5. DELETE 요청

  • id로 특정 todo를 찾아 삭제한다.

예시 9) DELETE 요청으로 id가 4인 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 = () => {
                // status 값이 200(OK)이면 정상 응답
                if(xhr.status === 200) {
                    document.querySelector('pre').textContent = xhr.response;
                }else{
                    console.error('Error', xhr.status, xhr.statusText);
                }
            };
        </script>
    </body>
</html>

 
결과

{}
반응형

+ Recent posts