iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
Modern Web

現在就學Node.js系列 第 13

RESTful API 設計 - Day13

  • 分享至 

  • xImage
  •  

什麼是 RESTful API?

REST(Representational State Transfer)是一種 資源導向 (Resource-oriented) 的 API 設計風格。

核心概念:

  • URL 表示資源(名詞)/notes/users/42
  • HTTP 方法表示動作GET / POST / PUT / PATCH / DELETE
  • 狀態碼表示結果201 Created404 Not Found204 No Content

👉 好處:

  • URL 簡潔、語意明確
  • 一致性 → 開發者光看 API 路徑與方法,就能懂用途
  • 可擴充性 → 隨專案成長,API 設計不會混亂

RESTful 對比範例

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 範例 開發簡易的API

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")
);

程式碼解析

1) app.use(express.json())

  • 解析 Content-Type: application/json 的 body
  • 沒這行 → req.body 會是 undefined,POST/PUT 會直接噴錯。

2) 假資料 notes

  • 用陣列模擬資料庫。
  • 後續可替換成 MongoDB 或其他 DB。

3) GET /notes

  • 回傳所有筆記。
  • 可擴充:分頁、排序、篩選 → GET /notes?page=2&limit=10&sort=-createdAt

4) POST /notes

  • 建立新筆記。
  • 重點:回應 201 Created,明確告訴 client「成功新增」。

5) PUT /notes/:id

  • 更新特定筆記。
  • PUT 在語意上表示「整體更新」。
  • 若只更新部分欄位,建議改用 PATCH

6) DELETE /notes/:id

  • 刪除資源。
  • 204 No Content = 成功,但不需要回傳內容。
  • 如果想要回訊息,可用 200 並回 JSON。

測試 API

使用 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 連線失敗

API 運作流程圖

[Client]
  │  GET/POST/PUT/DELETE /notes(/:id)
  ▼
[Express 應用程式]
  │  express.json() 解析 body
  ▼
[Route Handler (/notes...)]
  │  處理假資料(後續換成資料庫)
  ▼
[Response]
  │  狀態碼 + JSON 回傳

小結

今天學習:

  • RESTful API 設計的核心原則:資源導向 URL + HTTP 方法語意。
  • 如何用 Express.js 建立 /notes API。
  • 正確使用狀態碼(201, 204, 404…)來提升 API 易讀性。
  • API 測試方法(cURL/Postman)與流程圖示。

明天,我們要把路由「模組化」,拆分到 routes/notes.js,讓程式碼更有架構、更好維護。


上一篇
Express.js 中間件 (Middleware) - Day12
下一篇
Express.js Router 拆分 — 讓 API 更有架構 - Day14
系列文
現在就學Node.js15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言