๋ฐ์ํ
1. REST API๋?
- REST(Representational State Transfer) API๋ HTTP ํ๋กํ ์ฝ์ ๊ธฐ๋ฐ์ผ๋ก ํด๋ผ์ด์ธํธ์ ์๋ฒ๊ฐ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๋ฐฉ์์ด๋ค.
- CRUD(Create, Read, Update, Delete) ๊ธฐ๋ฅ์ ํตํด ๋ฐ์ดํฐ๋ฅผ ๊ด๋ฆฌํ ์ ์๋ค.
2. Express.js๋ฅผ ํ์ฉํ REST API ๊ตฌ์ถ
2.1. ํ๋ก์ ํธ ์ด๊ธฐํ ๋ฐ ํ์ ํจํค์ง ์ค์น
- ์๋ก์ด ํ๋ก์ ํธ ํด๋๋ฅผ ์์ฑํ๊ณ VSCode์์ ํด๋น ํด๋๋ก ์ด๋ํจ:
mkdir my-rest-api
cd my-rest-api
- npm์ ์ฌ์ฉํ์ฌ ํ๋ก์ ํธ๋ฅผ ์ด๊ธฐํํจ:
npm init -y
- Express.js ๋ฐ ๊ธฐํ ํ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ค์นํจ:
npm install express body-parser cors
2.2. ๊ธฐ๋ณธ ์๋ฒ ์ค์
- server.js ํ์ผ์ ์์ฑํ๊ณ ๋ค์๊ณผ ๊ฐ์ด Express ์๋ฒ๋ฅผ ์ค์ ํจ:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
728x90
๋ฐ์ํ
2.3. RESTful API ์๋ํฌ์ธํธ ๊ตฌํ (CRUD ๊ธฐ๋ฅ)
1) ๋ฐ์ดํฐ ์ ์ฅ์(Mock Data)
const users = [];
2) ์ฌ์ฉ์ ๋ชฉ๋ก ์กฐํ (Read)
app.get('/users', (req, res) => {
res.json(users);
});
3) ์๋ก์ด ์ฌ์ฉ์ ์ถ๊ฐ (Create)
app.post('/users', (req, res) => {
const user = req.body;
users.push(user);
res.status(201).json(user);
});
4) ์ฌ์ฉ์ ์ ๋ณด ์์ (Update)
app.put('/users/:id', (req, res) => {
const { id } = req.params;
const updatedUser = req.body;
const index = users.findIndex(user => user.id === parseInt(id));
if (index !== -1) {
users[index] = updatedUser;
res.json(updatedUser);
} else {
res.status(404).json({ message: 'User not found' });
}
});
5) ์ฌ์ฉ์ ์ญ์ (Delete)
app.delete('/users/:id', (req, res) => {
const { id } = req.params;
const index = users.findIndex(user => user.id === parseInt(id));
if (index !== -1) {
users.splice(index, 1);
res.json({ message: 'User deleted' });
} else {
res.status(404).json({ message: 'User not found' });
}
});
3. REST API ํ ์คํธ
3.1. Postman์ ํ์ฉํ API ํ ์คํธ
- Postman ์ค์น: Postman ๊ณต์ ์น์ฌ์ดํธ์์ ๋ค์ด๋ก๋ ํ ์ค์นํจ
- ์๋ฒ ์คํ: ํฐ๋ฏธ๋์์ ๋ค์ ๋ช ๋ น์ด ์คํ:
node server.js // nodemon server.js
- GET ์์ฒญ ํ
์คํธ:
- Postman์ ์ด๊ณ GET http://localhost:3000/users ์์ฒญ์ ๋ณด๋
- ๋น ๋ฐฐ์ด [ ] ์ด ์๋ต์ผ๋ก ์ค๋ฉด ์ ์ ๋์
- POST ์์ฒญ ํ
์คํธ:
- Postman์์ POST http://localhost:3000/users ์์ฒญ์ ์ ํ
- Body ํญ์์ raw๋ฅผ ์ ํํ๊ณ JSON ํ์์ผ๋ก ๋ฐ์ดํฐ ์ ๋ ฅ ํ Send ๋ฒํผ์ ๋๋ฌ ์์ฒญ์ ๋ณด๋ด๊ณ , ์ถ๊ฐ๋ ๋ฐ์ดํฐ๊ฐ ์๋ต์ผ๋ก ์ค๋์ง ํ์ธ:
{
id": 1,
"name": "5hr1rnp",
"email": "5hr1rnp@money.com"
}
- PUT ์์ฒญ ํ
์คํธ:
- PUT http://localhost:3000/users/1 ์์ฒญ์ ์ ํ.
- Body์ ๋ค์ ๋ฐ์ดํฐ๋ฅผ ์ ๋ ฅํ๊ณ ์ ์ก ํ ๋ณ๊ฒฝ๋ ๋ฐ์ดํฐ๊ฐ ์๋ต์ผ๋ก ์ค๋์ง ํ์ธ:
{
"id": 1,
"name": "5hr1rnp",
"email": "5hr1rnp@moremoney.com"
}
- DELETE ์์ฒญ ํ
์คํธ:
- DELETE http://localhost:3000/users/1 ์์ฒญ์ ๋ณด๋.
- ์๋ต์ผ๋ก { "message": "User deleted" } ๊ฐ ์ค๋ฉด ์ ์ ๋์ํจ.
4. ๋ง๋ฌด๋ฆฌ
- Node.js์ Express๋ฅผ ํ์ฉํ์ฌ ๊ธฐ๋ณธ์ ์ธ CRUD ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ REST API๋ฅผ ๊ตฌํํ์์
- ์ดํ์๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค๋ฅผ ์ฐ๋ํ์ฌ ๋์ฑ ํ์ฅ๋ API๋ฅผ ๊ฐ๋ฐํ๋ ๋ฐฉ๋ฒ์ ๋ค๋ฃฐ ์์ ์
๋ฐ์ํ