Queen Julia 2024. 6. 16. 16:53

RESTful API를 작성하는 방법에 대해 설명드리겠습니다. RESTful API는 REST(Representational State Transfer) 아키텍처 스타일을 따르는 API입니다.

 

REST는 클라이언트와 서버 간의 상호 작용을 규정하는 일련의 원칙과 제약 

 

RESTful API를 작성하는 데 필요한 단계와 주요 개념을 다음과 같이 설명합니다.

1. API 설계

1.1. 리소스 식별

RESTful API는 리소스 기반입니다. 리소스는 URL을 통해 고유하게 식별됩니다.

예를 들어, 사용자를 나타내는 리소스는 /users와 같은 경로를 사용할 수 있습니다.

1.2. HTTP 메서드

RESTful API는 리소스에 대한 작업을 수행하기 위해 HTTP 메서드를 사용합니다.

 

주요 HTTP 메서드

  • GET: 리소스 조회
  • POST: 리소스 생성
  • PUT: 리소스 전체 업데이트
  • PATCH: 리소스 부분 업데이트
  • DELETE: 리소스 삭제

1.3. 경로 설계

RESTful API의 경로는 명확하고 일관되게 설계되어야 합니다. 경로는 일반적으로 복수형 명사를 사용합니다.

예시:

  • GET /users: 모든 사용자 조회
  • GET /users/{id}: 특정 사용자 조회
  • POST /users: 새로운 사용자 생성
  • PUT /users/{id}: 특정 사용자 업데이트
  • DELETE /users/{id}: 특정 사용자 삭제

2. API 구현

RESTful API를 구현하는 예시로, Node.js와 Express를 사용한 간단한 API를 작성해 보겠습니다.

2.1. 프로젝트 설정

"make directory" 폴더 생성 

"change directory" 폴더 이동 

- 특정 디렉토리로 이동: cd new_directory

- 상위 디렉토리 이동: cd ..

- 홈 디렉토리 이동: cd ~

mkdir restful-api-example
cd restful-api-example
npm init -y
npm install express body-parser

2.2. 서버 설정

index.js 파일을 생성하고 다음과 같이 설정합니다.

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(bodyParser.json());

let users = [
  { id: 1, name: 'John Doe', email: 'john.doe@example.com' },
  { id: 2, name: 'Jane Smith', email: 'jane.smith@example.com' }
];

// GET /users
app.get('/users', (req, res) => {
  res.json(users);
});

// GET /users/:id
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found');
  res.json(user);
});

// POST /users
app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name,
    email: req.body.email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// PUT /users/:id
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found');

  user.name = req.body.name;
  user.email = req.body.email;
  res.json(user);
});

// DELETE /users/:id
app.delete('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
  if (userIndex === -1) return res.status(404).send('User not found');

  users.splice(userIndex, 1);
  res.status(204).send();
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

3. API 테스트

Postman, curl 등을 사용하여 API를 테스트합니다. 예를 들어, curl을 사용한 테스트는 다음과 같습니다:

  • 모든 사용자 조회: (GET) 
curl -X GET http://localhost:3000/users

 

  • 특정 사용자 조회: (GET) 
curl -X GET http://localhost:3000/users/1

 

  • 새로운 사용자 생성: (POST)
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "Alice Johnson", "email": "alice.johnson@example.com"}'

 

  • 사용자 업데이트: (PUT)
curl -X PUT http://localhost:3000/users/1 -H "Content-Type: application/json" -d '{"name": "John Doe Updated", "email": "john.doe.updated@example.com"}'

 

  • 사용자 삭제: (Delete)
curl -X DELETE http://localhost:3000/users/1

 

4. RESTful API의 베스트 프랙티스

  • 명확한 리소스 경로: 경로는 명확하고 일관성 있게 설정합니다.
  • 적절한 HTTP 메서드 사용: 리소스 작업에 적절한 HTTP 메서드를 사용합니다.
  • 상태 코드 사용: 적절한 HTTP 상태 코드를 반환합니다. 예: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found, 500 Internal Server Error.
  • JSON 형식 사용: 요청 및 응답 데이터는 JSON 형식을 사용합니다.
  • 문서화: API 엔드포인트, 요청/응답 형식, 예제, 오류 메시지 등을 상세히 문서화합니다.