2025-05-18 Postman 測試 /api/chat 的完整流程

2025-05-18 Postman 測試 /api/chat 的完整流程

Postman 測試 /api/chat 的完整流程「情境式操作」範例。


🎯 前置條件

  1. 你已經在 mcp-gateway 目錄下建立好 gateway.mjs

  2. 已經裝好 express / dotenv(你剛剛有做)。

  3. .env 裡面先不用放 API key(這樣會回 mock 回覆)。

  4. 啟動 server:

    1
    node gateway.mjs

    你應該會看到:

    1
    MCP gateway listening on 4000

🛠️ Postman 測試步驟

1. 開啟 Postman

  • 新增一個 Request
  • 選擇 POST

2. 設定 URL

在 URL 欄位輸入:

1
http://localhost:4000/api/chat

3. 設定 Header

Headers 分頁新增一筆:

1
2
Key: Content-Type
Value: application/json

4. 設定 Body

切換到 Body → raw → JSON,輸入:

1
2
3
4
{
"provider": "openai",
"messages": [{ "role": "user", "content": "hello" }]
}

5. 點擊 Send

如果你的 .env 沒有設定 API key,會回:

1
2
3
4
{
"provider": "openai",
"text": "[mock openai] 這是模擬回覆"
}

如果你有填 API key,會回傳真正的 OpenAI 回覆(例如 GPT 回應一段文字)。


📌 重點

  • http://localhost:4000/api/chat = 你的 API Gateway 入口。
  • Bodyprovider 決定用哪個 AI。
  • messages 是對話訊息(照 ChatGPT API 格式)。
  • 沒有 API key → 回 mock(方便測試)。

圖示化箭頭流程圖,用文字表示前端、Gateway、AI 之間的資料流向,包括 Header、Body 和 API Key 的位置,方便你快速理解整個流程。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
[ 前端 / Postman ]

│ POST http://localhost:4000/api/chat
│ Header:
│ Content-Type: application/json
│ Body:
│ {
│ "provider": "openai",
│ "messages": [{ "role":"user","content":"hello" }]
│ }

───────────────────────────────
│ MCP Gateway │
│ (gateway.mjs / Express) │
│ │
│ 1️⃣ 解析 Body → provider & messages
│ 2️⃣ 檢查 .env API Key
│ 3️⃣ 如果無 key → 回 mock
│ 4️⃣ 如果有 key → 呼叫 AI API
───────────────────────────────

│ POST https://api.openai.com/v1/chat/completions
│ (或 DeepSeek API)
│ Header:
│ Authorization: Bearer <API_KEY>
│ Content-Type: application/json
│ Body:
│ { model: "gpt-3.5-turbo", messages: [...] }

───────────────────────────────
│ AI Provider │
│ (OpenAI / DeepSeek) │
│ │
│ 回傳 JSON Response │
│ { choices: [...], ... } │
───────────────────────────────

│ Gateway 整理成統一格式

[ 前端 / Postman ]

│ Response JSON:
│ {
│ "provider": "openai",
│ "text": "AI 回覆文字",
│ "raw": { ...完整 AI 回覆... }
│ }

🔑 讀圖重點

  1. 前端 Header / Body

    • Header:告訴 Gateway 內容是 JSON
    • Body:告訴 Gateway 要用哪個 AI、訊息內容
  2. Gateway 的工作

    • 解析前端請求
    • 決定要 mock 還是呼叫真正 AI
    • 呼叫外部 API 時帶上 Authorization 與 Body
  3. Gateway 統一回傳

    • 不管是真實回覆還是 mock,都用統一格式給前端
  4. AI Provider

    • 接收 Gateway 封裝好的 request
    • 回傳結果給 Gateway