REST API 44

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

REST API의 구성

REST API는 자원, 행위, 표현의 3가지 요소로 구성된다.
REST는 자체 표현 구조로 구성되어 REST API만으로 HTTP 요청의 내용을 이해할 수 있다.

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

REST API 설계 원칙

REST에서 가장 중요한 기본적인 원칙은 두 가지다.

  1. URI는 리소스를 표현하는 데 집중하고
  2. 행위에 대한 정의는 HTTP 요청 메서드를 통해 한다.
HTTP 요청 메서드 종류 목적 페이로드
GET index/retrieve 모든/특정 리소스 취득 X
POST create 리소스 생성 O
PUT replace 리소스 전체 교체 O
PATCH modify 리소스 일부 수정 O
DELETE delete 모든/특정 리소스 삭제 X

JSON Server를 이용한 REST API 실습

HTTP 요청을 전송하고 응답을 받으려면 서버가 필요하다.
JSON Server를 사용해 가상 REST API 서버를 구축하여 HTTP 요청을 전송하고 응답을 받는 실습을 진행해보자.

JSON Server 설치

터미널에서 다음과 같이 JSON Server를 설치한다.

$ mkdir json-server-exam && cd json-server-exam
$ npm init -y
$ npm install json-server --save-dev

db.json 파일 생성

프로젝트 루트 폴더(/json-server-exam)에 다음과 같이 db.json 파일을 생성한다.

{
    "todos":[
        {
            "id":1,
            "content":"HTML",
            "completed":true
        },
        {
            "id":2,
            "content":"CSS",
            "completed":false
        },
        {
            "id":3,
            "content":"javascript",
            "completed":true
        }
    ]
}

JSON Server 실행

## 기본 포트(3000) 사용 / watch 옵션 적용
$ json-server --watch db.json

기본 포트는 3000이다. 포트를 변경하려면 port 옵션을 추가한다.

## 포트 변경 / watch 옵션 적용
$ json-server --watch db.json --port 5000

위와 같이 매번 명령어를 입력하는 것이 번거로우니 package.json 파일의 script를 다음과 같이 수정하여 JSON Server를 실행하여 보자.

{
    "name":"json-server-exam",
    "version":"1.0.0",
    "scripts":{
        "start":"json-server --watch db.json"
    },
    "devDependencies":{
        "json-server":"^0.16.1"
    }
}

터미널에서 npm start 명령어를 입력하여 JSON Server를 실행한다.

npm start

GET 요청

todos 리소스에서 모든 todo를 취득(index)한다.
JSON Server의 루트 폴더(/json-server-exam)에 public 폴더를 생성하고 JSON Server를 중단한 후 재실행한다.
public 폴더에 get.html을 추가하고 브라우저에서 http://localhost:3000/get.html 로 접속한다.

<!DOCTYPE html>
<html>
<body>
    <pre></pre>
    <script>
        const xhr = new XMLHttpRequest();
        xhr.open('GET', '/todos');
        xhr.send();
        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 요청 시에는 setRequestHeader 메서드를 사용하여 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정해야 한다.
public 폴더에 post.html을 추가하고 브라우저에서 http://localhost:3000/post.html 로 접속한다.

<!DOCTYPE html>
<html>
<body>
    <pre></pre>
    <script>
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/todos');
        xhr.setRequestHeader('content-type', 'application/json');
        xhr.send(JSON.stringify({id:4, content:'Vue',completed:false}));
        xhr.onload = () => {
            // 200(OK), 201(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>

PUT 요청

PUT은 특정 리소스 전체를 교체할 때 사용한다.
PUT 요청 시에는 setRequestHeader 메서드를 사용하여 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정해야 한다.
public 폴더에 put.html을 추가하고 브라우저에서 http://localhost:3000/put.html 로 접속한다.

<!DOCTYPE html>
<html>
<body>
    <pre></pre>
    <script>
        const xhr = new XMLHttpRequest();
        xhr.open('PUT', '/todos/4');
        xhr.setRequestHeader('content-type', 'application/json');
        xhr.send(JSON.stringify({id:4, content:'React',completed:true}));
        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는 특정 리소스의 일부를 수정할 때 사용한다.
PATCH 요청 시에는 setRequestHeader 메서드를 사용하여 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정해야 한다.
public 폴더에 patch.html을 추가하고 브라우저에서 http://localhost:3000/patch.html 로 접속한다.

<!DOCTYPE html>
<html>
<body>
    <pre></pre>
    <script>
        const xhr = new XMLHttpRequest();
        xhr.open('PATCH', '/todos/4');
        xhr.setRequestHeader('content-type', 'application/json');
        xhr.send(JSON.stringify({completed:false}));
        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를 삭제한다.
public 폴더에 delete.html을 추가하고 브라우저에서 http://localhost:3000/delete.html 로 접속한다.

<!DOCTYPE html>
<html>
<body>
    <pre></pre>
    <script>
        const xhr = new XMLHttpRequest();
        xhr.open('DELETE', '/todos/4');
        xhr.send();
        xhr.onload = () => {
            if(xhr.status === 200){
                document.querySelector('pre').textContent = xhr.response;
            }else{
                console.error('Error', xhr.status, xhr.statusText);
            }
        };
    </script>
</body>
</html>

웹브라우저에서 웹서버에 ajax를 위한 api인 fetch를 이용해서 REST API를 이용하는 방법
기계들의 대화법 - REST API
WEB2 - HTTP
Ajax - fetch