본문 바로가기
FRONT-END/JavaScript

[JavaScript] REST API와 JSON Server

by 랄라J 2020. 5. 26.

REST API

REST(Representational State Transfer)는 HTTP를 기반으로 클라이언트가 서버의 리소스에 접근하는 방식을 규정한 아키텍처이고, REST API는 REST를 기반으로 서비스 API를 구현한 것을 의미한다.

 

 

REST API의 구성

- 자원(Resource) : HTTP URI

- 행위(Verb) : HTTP 요청 메소드

- 표현(Representaitions) : HTTP 페이로드

 

REST API 설계 방침

- URI는 리소스를 표현해야 한다. (명사)

- 리소스에 대한 행위는 HTTP 요청 메소드로 표현한다. (GET, POST, PUT, PATCH, DELETE는 URI에 미표현)

 

 

JSON Server

JSON Server는 json 파일을 사용하여 REST API Mock server를 구축할 수 있는 툴이다.

 

 

JSON Server 설치

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

 

db.json 파일 생성

db.json 파일은 리소스를 제공하는 데이터베이스 역할을 한다.

 

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

 

JSON Server 실행

JSON Server가 데이터베이스 역할을 하는 db.json 파일의 변경을 감지하도록 하려면 watch 옵션을 추가하고, 기본 포트는 3000을 사용하는데 변경하려면 port 옵션을 추가한다.

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

매번 명령어를 입력하는 것은 번거로우니 package.json 파일의 scripts를 아래와 같이 수정하면 명령어를 짧게 실행할 수 있다.

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

 

$ npm start

 

GET 요청

public/get_1.html 추가 후 아래 코드 입력 뒤 http://localhost:3000/get_1.html 로 접속

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
</head>

<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>

 

특정 id값으로 가져오는 방법

위 코드에서 open 시 'GET' 요청을 보낼 때 아래와 같이 원하는 정보를 함께보낸다.

xhr.open('GET', '/todos/1');

 

POST 요청

setRequestHeader를 설정하고, send 시 보낼 데이터를 입력하는데, JSON 형태로 객체를 바꿔 보낸다.

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<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: 'React',
      completed: false
    }));
    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은 특정 리소스의 전체를 교체할 때 사용한다.

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<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_2',
      complement: 'true'
    }))

    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>

 

PATCH 요청

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

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <pre></pre>
  <script>
    const xhr = new XMLHttpRequest();

    xhr.open('PUT', '/todos/4');
    xhr.setRequestHeader('content-type', 'application/json');

    xhr.send(JSON.stringify({
      complement: 'false'
    }))

    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>

 

DELETE 요청

위 코드에서 아래만 수정하면 된다.

 xhr.open('DELETE', '/todos/4');
 xhr.send();

 

반응형

댓글