JavaScript
REST API
Hun-bot
2022. 7. 11. 16:18
728x90
반응형
REST : HTTP를 기반으로 클라이언트가 서버의 리소스에 접근하는 방식을 규정한 아키텍처
구성 요소 | 내용 | 표현 방법 |
자원 | 자원 | URI(엔드포인트) |
행위 | 자원에 대한 행위 | HTTP 요청 메서드 |
표현 | 자원에 대한 행위의 구체적 내용 | 페이로드 |
*페이로드 => 사용에 있어서 전송되는 데이터를 뜻함, 페이로드라는 용어는 큰 데이터 덩어리 중에 '흥미 있는' 데이터를 구별하는 데 사용
REST API 설계 원칙
1. URI는 리소스를 표현해야 한다 ( 명사 사용 )
# bad
GET /getTodos/1
GET /todos/show/1
# good
GET /todos/1
2. 리소스에 대한 행위는 HTTP 요청 메서드로 표현한다
HTTP 요청 메서드 | 종류 | 목적 | 페이로드 |
GET | index/retrieve | 모든/특정 리소스 취득 | X |
POST | create | 리소스 생성 | O |
PUT | replace | 리소스의 전체 교체 | O |
PATCH | modify | 리소스의 일부 수정 | O |
DELETE | delete | 모든/특정 리소스 삭제 | X |
# bad
GET /todos/delete/1
# good
DELETE /todos/1
JSON Server를 이용한 실습
JSON Server 설치후 db.json을 생성해 실습해보자
GET
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<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('GET','/todos/1')
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
<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=()=>{
if(xhr.status===200 || xhr.status===201){
document.querySelector('pre').textContent=xhr.response
}
else{
console.error('Error',xhr.status,xhr.statusText)
}
}
</script>
PUT
<script>
const xhr=new XMLHttpRequest();
xhr.open('PUT','/todos')
xhr.setRequestHeader('content-type','application/json')
xhr.send(JSON.stringify({id:4,content:'Changed React',completed:true}))
xhr.onload=()=>{
if(xhr.status===200){
document.querySelector('pre').textContent=xhr.response
}
else{
console.error('Error',xhr.status,xhr.statusText)
}
}
</script>
PATCH
<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>
DELETE
<script>
const xhr=new XMLHttpRequest();
xhr.open('DELETE','/todos/4')
xhr.send()
xhr.onload=()=>{
if(xhr.status===200 || xhr.status===201){
document.querySelector('pre').textContent=xhr.response
}
else{
console.error('Error',xhr.status,xhr.statusText)
}
}
</script>
728x90
반응형