REST(Representational State Transfer)是一種 資源導向 (Resource-oriented) 的 API 設計風格。
核心概念:
/notes
、/users/42
GET
/ POST
/ PUT
/ PATCH
/ DELETE
201 Created
、404 Not Found
、204 No Content
…👉 好處:
URL 只描述「資源」,行為交給 HTTP 方法來表達。
操作 | ❌ 不符合 REST (RPC 風格) | ✅ 符合 REST (資源導向) |
---|---|---|
取得所有筆記 | GET /getAllNotes |
GET /notes |
取得單一筆記 | GET /getNoteById?id=1 |
GET /notes/1 |
新增筆記 | POST /createNote |
POST /notes |
更新筆記 | POST /updateNote?id=1 |
PUT /notes/1 |
刪除筆記 | POST /deleteNote?id=1 |
DELETE /notes/1 |
用 Express.js 來實作一個簡單的CRUD筆記 API:
import express from "express";
const app = express();
app.use(express.json()); // 處理 JSON body
let notes = [
{ id: 1, title: "第一則筆記" },
{ id: 2, title: "第二則筆記" }
];
// 1. 取得所有筆記
app.get("/notes", (req, res) => {
res.json(notes);
});
// 2. 新增筆記
app.post("/notes", (req, res) => {
const newNote = { id: Date.now(), title: req.body.title };
notes.push(newNote);
res.status(201).json(newNote);
});
// 3. 更新筆記
app.put("/notes/:id", (req, res) => {
const note = notes.find(n => n.id == req.params.id);
if (!note) return res.status(404).json({ error: "找不到筆記" });
note.title = req.body.title;
res.json(note);
});
// 4. 刪除筆記
app.delete("/notes/:id", (req, res) => {
notes = notes.filter(n => n.id != req.params.id);
res.status(204).send(); // 204 = No Content
});
app.listen(3000, () =>
console.log("🚀 伺服器運行中:http://localhost:3000")
);
app.use(express.json())
Content-Type: application/json
的 bodyreq.body
會是 undefined
,POST/PUT 會直接噴錯。notes
GET /notes
GET /notes?page=2&limit=10&sort=-createdAt
POST /notes
PUT /notes/:id
DELETE /notes/:id
200
並回 JSON。使用 cURL 測試:
# 取得所有
curl http://localhost:3000/notes
# 新增
curl -X POST http://localhost:3000/notes \
-H "Content-Type: application/json" \
-d '{"title":"新的筆記"}'
# 更新
curl -X PUT http://localhost:3000/notes/1 \
-H "Content-Type: application/json" \
-d '{"title":"改過的標題"}'
# 刪除
curl -X DELETE http://localhost:3000/notes/1
狀態碼 | 意義 | 範例 |
---|---|---|
200 OK | 查詢/更新成功 | GET /notes/1 |
201 Created | 成功建立新資源 | POST /notes |
204 No Content | 刪除成功,無需回應內容 | DELETE /notes/1 |
400 Bad Request | 請求不合法 | 缺少欄位 |
404 Not Found | 找不到資源 | GET /notes/999 |
500 Internal Server Error | 伺服器錯誤 | DB 連線失敗 |
[Client]
│ GET/POST/PUT/DELETE /notes(/:id)
▼
[Express 應用程式]
│ express.json() 解析 body
▼
[Route Handler (/notes...)]
│ 處理假資料(後續換成資料庫)
▼
[Response]
│ 狀態碼 + JSON 回傳
今天學習:
/notes
API。明天,我們要把路由「模組化」,拆分到 routes/notes.js
,讓程式碼更有架構、更好維護。