REST API

자몽·2021년 7월 3일
1

node.js

목록 보기
1/1

REST API

📕 REST API란?

HTTP 프로토콜 장점을 살릴 수 있는 네트워크 기반 아키텍처로,
REST 기반으로 서비스 API를 구현한 것이다.

📘 REST API 설계

  1. URI는 정보의 자원을 표현해야 한다.
  2. 자원에 대한 행위는 HTTP Method(GET, POST, PUT, DELETE)로 표현한다.

📒 HTTP 메서드

메서드설명
GET데이터를 조회할 때 사용
POST데이터를 등록할 때 사용
DELETE데이터를 지울 때 사용
PUT데이터를 새 정보로 통째로 교체할 때 사용
PATCH데이터의 특정 필드를 수정할 때 사용

📗 REST API의 예시

종류기능
POST /posts포스트 작성
GET /posts포스트 목록 조회
GET /posts/:id특정 포스트 조회
DELETE /posts/:id특정 포스트 삭제
PATCH /posts/:id특정 포스트 업데이트
POST /posts/:id/comments특정 포스트에 덧글 등록
GET /posts/:id/comments특정 포스트의 덧글 목록 조회
DELETE /posts/:id/comments/:commentId특정 포스트의 특정 덧글 삭제

📙 컨트롤러 파일 예시

다음은 posts.ctrl.js 파일이다.

let postId = 1;
const posts = [
    {
        id: 1,
        title: '제목',
        body: '내용',
    },
];

// POST 포스트 작성
exports.write = ctx => {
    const { title, body } = ctx.request.body;
    postId += 1;
    const post = { id: postId, title, body };
    posts.push(post);
    ctx.body = post;
};

// GET 포스트 조회
exports.list = ctx => {
    ctx.body = posts;
};

// GET 특정 포스트 조회
exports.read = ctx => {
    const { id } = ctx.params;
    const post = posts.find(p => p.id.toString() === id);
    if (!post) {
        ctx.status = 404;
        ctx.body = {
            message: '포스트가 존재하지 않습니다',
        };
        return;
    }
    ctx.body = post;
};

// DELETE 특정 포스트 제거
exports.remove = ctx => {
    const { id } = ctx.params;
    const index = posts.findIndex(p => p.id.toString() === id);
    if (index === -1) {
        ctx.status = 404;
        ctx.body = {
            message: '포스트가 존재하지 않습니다.',
        };
        return;
    }
    posts.splice(index, 1);
    ctx.status = 204;
};

// PUT 포스트 수정(교체)
// 전체 포스트 정보를 입력하여 데이터를 통째로 교체할 떄 사용
exports.replace = ctx => {
    const { id } = ctx.params;
    const index = posts.findIndex(p => p.id.toString() === id);
    if (index === -1) {
        ctx.status = 404;
        ctx.body = {
            message: '포스트가 존재하지 않습니다.',
        };
        return;
    }
    posts[index] = {
        id,
        ...ctx.request.body,
    };
    ctx.body = posts[index];
};

// PATCH 포스트 수정(특정 필드 변경)
exports.update = ctx => {
    const { id } = ctx.params;
    const index = posts.findIndex(p => p.id.toString() === id);
    if (index === -1) {
        ctx.status = 404;
        ctx.body = {
            message: '포스트가 존재하지 않습니다.',
        };
        return;
    }
    posts[index] = {
        ...posts[index],
        ...ctx.request.body,
    };
    ctx.body = posts[index];
}

참고(리액트를 다루는 기술)

profile
꾸준하게 공부하기

0개의 댓글