구성 요소 | 내용 | 표현 방법 |
---|---|---|
자원 (resource) | 자원 | URI(엔드포인트) |
행위 (verb) | 자원에 대한 행위 | HTTP 요청 메서드 |
표현 (representations) | 자원에 대한 행위의 구체적 내용 | 페이로드 |
🔍 페이로드란? (payload)
: 전송의 근본적인 목적이 되는 데이터의 일부분으로 그 데이터와 함께 전송되는 헤더와 메타데이터와 같은 데이터는 제외함
1. URI는 리소스를 표현해야 한다.
# bad
GET /getTodos/1
GET /todos/show/1
# good
GET /todos/1
2. 리소스에 대한 행위는 HTTP 요청 메서드로 표현한다.
< HTTP 요청 메서드 5가지 >
HTTP 요청 메서드| 종류 | 목적 | 페이로드
|:----------:|:----------:|:----------:|:----------:|
GET| index/retrieve| 모든/특정 리소스 취득| X
POST| create| 리소스 생성| O
PUT| replace| 리소스의 전체 교체| O
PATCH| modify| 리소스의 일부 수정| O
DELETE| delete| 모든/특정 리소스 삭제| X
# bad : URI에 리소스 삭제 행위인 delete를 표현함
GET /todos/delete/1
# good : 리소스 삭제 행위를 HTTP 요청 메서드인 DELETE로 표현함
DELETE /todos/1
HTTP 요청을 전송 & 응답 받으려면 서버가 필요함
-> JSON Server를 사용하여 가상 REST API 서버 구축해서 실습해보자!
mkdir json-server-exam && cd json-server-exam
npm init -y
npm install json-server --save-dev
{
"todos": [
{
"id": 1,
"content": "HTML",
"completed": true
},
{
"id": 2,
"content": "CSS",
"completed": false
},
{
"id": 3,
"content": "Javascript",
"completed": true
}
]
}
## 기본 포트(3000) 사용 / watch 옵션 적용
json-server--watch db.json
## 포트 5000으로 변경 / watch 옵션 적용
json-server--watch db.json --port 5000
{
"name": "json-server-exam",
"version": "1.0.0",
"scripts": {
"start": "json-server --watch db.json"
},
"devDependencies": {
"json-server": "^0.16.1"
}
}
npm start
명령어 입력1) json-server-exam/public 생성, JSON Server 중단 후 재실행
2) 다음과 같이 get_index.html 추가
3) http://localhost:3000/get_index.html로 접속
<!DOCTYPE html>
<html>
<body>
<pre></pre>
<script>
// XMLHttpRequest 객체 생성
const xhr = new XMLHttpRequest();
// HTTP 요청 초기화
// todos 리소스에서 모든 todo를 취득(index)
xhr.open('GET', '/todos');
// HTTP 요청 전송
xhr.send();
// load 이벤트는 요청이 성공적으로 완료된 경우 발생한다.
xhr.onload = () => {
// status 프로퍼티 값이 200이면 정상적으로 응답된 상태다.
if (xhr.status === 200) {
document.querySelector('pre').textContent = xhr.response;
} else {
console.error('Error', xhr.status, xhr.statusText);
}
};
</script>
</body>
</html>
1) public 폴더에 다음과 같이 get_retrieve.html 추가
2) http://localhost:3000/get_retrieve.html로 접속
<!DOCTYPE html>
<html>
<body>
<pre></pre>
<script>
// XMLHttpRequest 객체 생성
const xhr = new XMLHttpRequest();
// HTTP 요청 초기화
// todos 리소스에서 id를 사용하여 특정 todo를 취득(retrieve)
xhr.open('GET', '/todos/1');
// HTTP 요청 전송
xhr.send();
// load 이벤트는 요청이 성공적으로 완료된 경우 발생한다.
xhr.onload = () => {
// status 프로퍼티 값이 200이면 정상적으로 응답된 상태다.
if (xhr.status === 200) {
document.querySelector('pre').textContent = xhr.response;
} else {
console.error('Error', xhr.status, xhr.statusText);
}
};
</script>
</body>
</html>
1) public 폴더에 다음과 같이 post.html 추가
2) http://localhost:3000/post.html로 접속
<!DOCTYPE html>
<html>
<body>
<pre></pre>
<script>
// XMLHttpRequest 객체 생성
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 = () => {
// status 프로퍼티 값이 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>
1) public 폴더에 다음과 같이 put.html 추가
2) http://localhost:3000/put.html로 접속
<!DOCTYPE html>
<html>
<body>
<pre></pre>
<script>
// XMLHttpRequest 객체 생성
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 = () => {
// status 프로퍼티 값이 200이면 정상적으로 응답된 상태다.
if (xhr.status === 200) {
document.querySelector('pre').textContent = xhr.response;
} else {
console.error('Error', xhr.status, xhr.statusText);
}
};
</script>
</body>
</html>
1) public 폴더에 다음과 같이 patch.html 추가
2) http://localhost:3000/patch.html로 접속
<!DOCTYPE html>
<html>
<body>
<pre></pre>
<script>
// XMLHttpRequest 객체 생성
const xhr = new XMLHttpRequest();
// HTTP 요청 초기화
// todos 리소스의 id로 todo를 특정하여 completed만 수정
xhr.open('PATCH', '/todos/4');
// 요청 몸체에 담아 서버로 전송할 페이로드의 MIME 타입을 지정
xhr.setRequestHeader('content-type', 'application/json');
// HTTP 요청 전송
// 리소스를 수정하기 위해 페이로드를 서버에 전송해야 한다.
xhr.send(JSON.stringify({ completed: false }));
// load 이벤트는 요청이 성공적으로 완료된 경우 발생한다.
xhr.onload = () => {
// status 프로퍼티 값이 200이면 정상적으로 응답된 상태다.
if (xhr.status === 200) {
document.querySelector('pre').textContent = xhr.response;
} else {
console.error('Error', xhr.status, xhr.statusText);
}
};
</script>
</body>
</html>
1) public 폴더에 다음과 같이 delete.html 추가
2) http://localhost:3000/delete.html로 접속
<!DOCTYPE html>
<html>
<body>
<pre></pre>
<script>
// XMLHttpRequest 객체 생성
const xhr = new XMLHttpRequest();
// HTTP 요청 초기화
// todos 리소스에서 id를 사용하여 todo를 삭제한다.
xhr.open('DELETE', '/todos/4');
// HTTP 요청 전송
xhr.send();
// load 이벤트는 요청이 성공적으로 완료된 경우 발생한다.
xhr.onload = () => {
// status 프로퍼티 값이 200이면 정상적으로 응답된 상태다.
if (xhr.status === 200) {
document.querySelector('pre').textContent = xhr.response;
} else {
console.error('Error', xhr.status, xhr.statusText);
}
};
</script>
</body>
</html>