뚜벅

모던 자바스크립트 Deep Dive - REST API 본문

JavaScript

모던 자바스크립트 Deep Dive - REST API

초코맛젤리 2022. 12. 31. 03:53

REST

REST란 HTTP를 기반으로 클라이언트가 서버의 리소스에 접근하는 방식을 규정한 아키텍쳐이다. 

 

- REST의 기본원칙을 성실히 치킨 서비스 디자인을 RESTful이라고 표현한다.

- REST API는 REST를 기반으로 서비스 API를 구현한 것을 의미한다. 

 

REST API 구성

- 자원 :  URL

- 행위 :  HTTP 요청 메서드

- 표현 :  페이로드 

 

REST API 설계 원칙

1. URL는 리소스를 표현해야 한다.

리소스를 식별할 수 있는 이름은 동사보다는 명사를 사용한다.

# bad
GET /getTodos/1

# good
GET /Todos/1

2. 리소스에 대한 행위는 HTTP 요청 메서드로 표현한다.

요청 메서드는 크게 5가지가 있다. (GET, POST, PUT, PATCH, DELETE)

 

HTTP 요청 메서드 종류 목적 페이로드
GET index / retrieve 모든 / 특정 리소스 취득 x
POST create 리소스 생성 o
PUT replace 리소스의 전체 교체 o
PATCH modify 리소스의 일부 수정 o
DELETE  delete 모든 / 특정 리소스 삭제 x

 

fetch를 사용하여 실습!

브라우저에 내장된 함수이기 때문에 따로 설치없이 바로 사용할 수 있기 때문에 fetch를 예시로 들겠습니다.

 

- GET: 보낼 데이터가 없기 때문에, headers와 body 옵션이 필요 없다. 

// GET 요청
fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((json) => console.log(json));

- POST: fetch(url, {method, headers, body})

  • method = HTTP 요청 메서드
  • headers = HTTP 헤더
    • "Content-Type" : 요청 몸체에 담아 전송할 데이터의 타입 정보를 표현한다. 
  • body = 전송할 데이터 (페이로드)
// POST 
// 이때 페이로드값이 객체인경우 직렬화 한다음 전달한다.
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

- PUT : fetch(url, {method, headers, body})

// PUT
fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT',
  body: JSON.stringify({
    id: 1,
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

- PATCH : fetch(url, {method, headers, body})

// PATCH
fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PATCH',
  body: JSON.stringify({
    title: 'foo',
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

- DELETE : fetch(url,{method})

// DELETE
fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'DELETE',
});