REST API

2022. 7. 11. 16:18·JavaScript
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
반응형
저작자표시 (새창열림)

'JavaScript' 카테고리의 다른 글

제너레이터와 async/await  (1) 2022.07.12
프로미스  (1) 2022.07.11
Ajax  (0) 2022.07.11
비동기 프로그래밍  (1) 2022.07.10
DOM/디바운스,스로틀  (0) 2022.07.07
'JavaScript' 카테고리의 다른 글
  • 제너레이터와 async/await
  • 프로미스
  • Ajax
  • 비동기 프로그래밍
Hun-bot
Hun-bot
IT를 중심으로 다양한 것
  • Hun-bot
    로봇이 만드는 눈사람
    Hun-bot
  • 전체
    오늘
    어제
    • All Article (128)
      • Programmers (6)
        • TIP (1)
        • SQL (2)
        • LV1 (1)
        • LV2 (2)
        • LV3 (0)
      • Baekjoon (31)
        • Bronze (10)
        • Silver (19)
        • Gold (2)
        • Platinum (0)
        • Diamond (0)
      • Leetcode (0)
        • Easy (0)
        • Medium (0)
        • Hard (0)
        • SQL (0)
      • 알고리즘(Algorithm) (42)
      • JavaScript (40)
      • Linux (7)
      • JSP (1)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      Algorithm
      알고리즘
      백준
      JavaScript #Set #Collection
      Vue #Vue.js #정리
      프로그래머스 #자바스크립트 #JS
      BaekJoon
      JS #클래스
      JS #JavaScript #프로그래머스 #알고리즘
      Python #알고리즘
      JS #프로그래머스 #숫자의표현 #알고리즘
      LeetCode #JS #Javascript #Algorithm
      JS #정규표현식
      JSP #Vscode #톰켓 #Tomcat #Java #Web #jdk
      JS #JavaScript #프로그래머스 #카카오
      고득점 Kit
      Programmers
      티스토리챌린지
      리눅스
      Javascript
      자바스크립트
      자바스크립트 #연습문제
      알고리즘 #Algorithm
      SQL
      프로그래머스
      JS #javascript #객체 #Object
      c++
      async await #js #문법 #자바스크립트 #비동기
      리눅스 #입문
      오블완
    • 최근 댓글

    • hELLO· Designed By정상우.v4.10.3
    Hun-bot
    REST API
    상단으로

    티스토리툴바

    티스토리툴바