iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
自我挑戰組

API 全攻略系列 第 16

Day 16: API 路由與參數設計

  • 分享至 

  • xImage
  •  

前言

在 RESTful API 中, 路由(Route)參數(Parameter) 是設計 API 的核心。好的路由設計能讓 API 清晰易懂,而參數則能讓 API 更加靈活。今天我們會用 Node.js / Express 來示範如何設計 API 路由與參數。


路由設計基本原則

1.使用名詞,而不是動詞

  • X /getTodos
  • O /api/todos

2.用複數表示集合

  • /api/todos -> 取得所有 Todo
  • /api/todos/1 -> 取得 ID 為 1 的 Todo

3.層級結構清晰

  • /api/users/1/todos -> 取得某使用者的所有 Todo

路由中的參數

Express 提供兩種主要的參數形式:

1.路徑參數(Path Parameter)

  • 通常用於指定特定資源,例如 ID
  • /api/todos/:id

2.查詢參數(Query Parameter)

  • 通常用於篩選、搜尋、排序
  • /api/todos?done=true

範例程式碼

我們在昨天的 index.js 基礎上,加入參數功能:

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

app.use(express.json());

const todos = [
  { id: 1, task: '學習 API 基礎', done: true },
  { id: 2, task: '撰寫第一個 API', done: false },
  { id: 3, task: '理解路由設計', done: false }
];

// 取得所有 Todo
app.get('/api/todos', (req, res) => {
  // 使用查詢參數篩選
  const { done } = req.query;
  if (done) {
    const filtered = todos.filter(todo => String(todo.done) === done);
    return res.json(filtered);
  }
  res.json(todos);
});

// 取得單一 Todo(路徑參數)
app.get('/api/todos/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const todo = todos.find(t => t.id === id);
  if (!todo) {
    return res.status(404).json({ error: 'Todo not found' });
  }
  res.json(todo);
});

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

測試方式

1.啟動伺服器:

node index.js

2.測試路由:


小結

  • 路徑參數 適合用來定位單一資源(例如 ID)。
  • 查詢參數 適合用來篩選或排序資料。
  • API 路由設計需要簡潔、直觀,這樣才能讓使用者快速理解。

上一篇
Day 15: 建立第一個簡單的 API(Node.js / Express)
下一篇
Day 17: API 的 CRUD 設計(建立、讀取、更新、刪除)
系列文
API 全攻略17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言