iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
自我挑戰組

API 全攻略系列 第 27

Day 27:整合多個 API(Aggregator Pattern)

  • 分享至 

  • xImage
  •  

前言

在前面的章節中,我們學會了如何建立自己的 API,也學過如何使用 **第三方 API(例如 GitHub API)。**那麼如果一個應用程式需要 同時使用多個 API ,應該如何設計呢?這時候,就會用到 Aggregator Pattern(聚合模式)


什麼是 Aggregator Pattern?

Aggregator Pattern 的核心概念是:
建立一個「中間層 API」,負責呼叫多個後端 API,並將結果整合後回傳給客戶端。

好處是:

  • 減少前端複雜度(前端不用呼叫多個 API)
  • 提高效能(可以並行請求後端 API,再合併結果)
  • 增加可維護性(邏輯集中在 Aggregator 層)

實務範例:Todo + GitHub

假設我們有一個 Todo 應用程式:

  • 自建的 Todo API:管理任務清單
  • 第三方的 GitHub API:顯示使用者資訊
    我們希望回傳的 JSON 長這樣:
{
  "todo": {
    "id": 1,
    "title": "完成 API 教學",
    "completed": false
  },
  "author": {
    "login": "octocat",
    "name": "The Octocat",
    "public_repos": 8
  }
}

Aggregator API 的實作

安裝 node-fetch

npm install node-fetch

建立 Aggregator

import express from "express";
import fetch from "node-fetch";

const app = express();

// 假設本地有一個 Todo API
const TODO_API = "http://localhost:3000/todos/1";
const GITHUB_API = "https://api.github.com/users/octocat";

app.get("/aggregated", async (req, res) => {
  try {
    // 並行請求兩個 API
    const [todoRes, githubRes] = await Promise.all([
      fetch(TODO_API),
      fetch(GITHUB_API)
    ]);

    const todo = await todoRes.json();
    const author = await githubRes.json();

    res.json({
      todo,
      author: {
        login: author.login,
        name: author.name,
        public_repos: author.public_repos
      }
    });
  } catch (error) {
    res.status(500).json({ error: "Aggregator API Failed" });
  }
});

app.listen(4000, () => {
  console.log("Aggregator API running on http://localhost:4000");
});

現在,客戶端只要呼叫:

GET http://localhost:4000/aggregated

就能同時拿到 Todo 與 GitHub 使用者的資料。


Aggregator Pattern 的應用場景

1.電商網站

  • 整合「商品 API」+「庫存 API」+「物流 API」
  • 客戶端只需呼叫一次 API,就能得到完整資訊

2.金融服務

  • 整合「帳戶 API」+「交易 API」+「外部匯率 API」
  • 提供一個統一的 Dashboard

3.旅遊平台

  • 整合「飯店 API」+「航班 API」+「租車 API」
  • 回傳一個完整的行程建議

小結

  • Aggregator Pattern 將多個 API 整合成一個統一回應,減少前端負擔。
  • 可以透過 並行請求 提升效能。
  • 常見應用場景包含 電商、金融、旅遊 等需要整合多個來源的系統。

上一篇
Day 26:第三方 API 使用(以 GitHub API 為例)
下一篇
Day 28:API 的版本管理策略
系列文
API 全攻略28
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言