API 測試與除錯指南:從 cURL 到線上工具的介面除錯全攻略

開發工具

HTTP 請求方法

方法 用途 冪等 安全
GET 取得資源 ✅ ✅
POST 建立資源 ❌ ❌
PUT 全量更新 ✅ ❌
PATCH 部分更新 ❌ ❌
DELETE 刪除資源 ✅ ❌
HEAD 取得標頭資訊 ✅ ✅
OPTIONS 跨域預檢 ✅ ✅

常用請求標頭

標頭 說明 範例
Content-Type 請求主體格式 application/json
Accept 期望的回應格式 application/json
Authorization 認證資訊 Bearer token...
User-Agent 用戶端識別 Mozilla/5.0...
Cookie Cookie session=abc123
X-Request-ID 請求追蹤 ID UUID

Content-Type 常見值

值 用途
application/json JSON 資料
application/x-www-form-urlencoded 表單資料
multipart/form-data 檔案上傳
text/plain 純文字
text/html HTML

認證方式

1. Bearer Token(最常用)

# cURL
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..." \
  https://api.example.com/users

# JavaScript
fetch('https://api.example.com/users', {
  headers: {
    'Authorization': 'Bearer eyJhbGciOiJIUzI1NiJ9...',
  },
});

2. Basic Auth

# cURL(自動編碼)
curl -u username:password https://api.example.com/users

# 手動編碼
# Base64("username:password") = "dXNlcm5hbWU6cGFzc3dvcmQ="
curl -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" \
  https://api.example.com/users

3. API Key

# 方式一:Header
curl -H "X-API-Key: your-api-key" \
  https://api.example.com/users

# 方式二:Query 參數
curl "https://api.example.com/users?api_key=your-api-key"

cURL 指令詳解

基礎 GET 請求

# 最簡單的 GET
curl https://api.example.com/users

# 顯示回應標頭
curl -i https://api.example.com/users

# 只顯示回應標頭
curl -I https://api.example.com/users

# 跟隨重新導向
curl -L https://example.com/redirect

POST 請求

# JSON 資料
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice", "email": "alice@example.com"}'

# 表單資料
curl -X POST https://api.example.com/users \
  -d "name=Alice&email=alice@example.com"

# 檔案上傳
curl -X POST https://api.example.com/upload \
  -F "file=@photo.jpg" \
  -F "description=My photo"

進階選項

# 逾時設定
curl --connect-timeout 5 --max-time 30 https://api.example.com

# 輸出到檔案
curl -o response.json https://api.example.com/users

# 靜默模式(不顯示進度)
curl -s https://api.example.com/users

# 詳細輸出(除錯用)
curl -v https://api.example.com/users

# 忽略 SSL 憑證驗證(僅開發環境)
curl -k https://self-signed.example.com

# 代理
curl -x http://proxy:8080 https://api.example.com

# Cookie
curl -b "session=abc123" https://api.example.com/users

# 儲存和發送 Cookie
curl -c cookies.txt -b cookies.txt https://api.example.com/users

常見 HTTP 狀態碼

狀態碼 含義 常見原因
200 OK 成功
201 Created POST 建立成功
204 No Content DELETE 成功
301 Moved Permanently 永久重新導向
304 Not Modified 快取命中
400 Bad Request 參數錯誤
401 Unauthorized 未認證
403 Forbidden 無權限
404 Not Found 資源不存在
409 Conflict 資源衝突
422 Unprocessable Entity 驗證失敗
429 Too Many Requests 限流
500 Internal Server Error 伺服器錯誤
502 Bad Gateway 上游服務不可用
503 Service Unavailable 服務過載

使用工具庫測試 API

cURL 轉程式

  1. 開啟 cURL 轉程式工具
  2. 貼上 cURL 指令
  3. 選擇目標語言(JavaScript/Python/Go/Java 等)
  4. 複製產生的程式

範例

# 輸入 cURL
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer token123" \
  -d '{"name": "Alice"}'

轉換為 JavaScript:

const response = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123',
  },
  body: JSON.stringify({ name: 'Alice' }),
});
const data = await response.json();

API 除錯技巧

1. 檢視完整請求/回應

# -v 顯示詳細資訊
curl -v https://api.example.com/users

# 輸出:
> GET /users HTTP/1.1          ← 請求行
> Host: api.example.com        ← 請求標頭
> Authorization: Bearer ...
>
< HTTP/1.1 200 OK              ← 回應行
< Content-Type: application/json ← 回應標頭
< X-RateLimit-Remaining: 99
<
[{"id": 1, "name": "Alice"}]   ← 回應主體

2. 格式化 JSON 回應

# 使用 jq 格式化
curl -s https://api.example.com/users | jq

# 使用 python
curl -s https://api.example.com/users | python -m json.tool

# 或用工具庫的 JSON 格式化工具

3. 測量回應時間

# 詳細時間統計
curl -w "DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n" \
  -o /dev/null -s https://api.example.com/users

# 輸出:
# DNS: 0.012s
# Connect: 0.035s
# TTFB: 0.120s
# Total: 0.125s

4. 排查 CORS 問題

瀏覽器報錯:
Access to fetch at 'https://api.example.com' from origin 'https://app.example.com'
has been blocked by CORS policy

排查步驟:
1. 檢查 OPTIONS 預檢請求
   curl -X OPTIONS -H "Origin: https://app.example.com" \
     -H "Access-Control-Request-Method: POST" \
     -i https://api.example.com/users

2. 檢查回應標頭
   Access-Control-Allow-Origin: https://app.example.com
   Access-Control-Allow-Methods: GET, POST, PUT, DELETE
   Access-Control-Allow-Headers: Content-Type, Authorization
   Access-Control-Max-Age: 86400

5. 排查認證問題

401 Unauthorized 排查:
1. Token 是否過期?→ 用 JWT 解碼工具查看 exp
2. Token 格式是否正確?→ 檢查 Bearer 前綴
3. Token 是否發送?→ curl -v 檢查請求標頭

403 Forbidden 排查:
1. 使用者是否有權限?→ 檢查使用者角色
2. IP 是否在白名單?→ 檢查伺服器日誌
3. 是否超過頻率限制?→ 檢查 429 狀態碼

API 測試最佳實踐

1. 環境變數管理

# 使用環境變數儲存敏感資訊
export API_BASE="https://api.example.com"
export API_TOKEN="your-token"

curl -H "Authorization: Bearer $API_TOKEN" "$API_BASE/users"

2. 請求集合

#!/bin/bash
# api-test.sh

BASE="https://api.example.com"
TOKEN="Bearer $API_TOKEN"
HEADER="-H 'Content-Type: application/json' -H 'Authorization: $TOKEN'"

# 取得使用者列表
get_users() { curl -s $HEADER "$BASE/users" | jq; }

# 建立使用者
create_user() { curl -s -X POST $HEADER -d "$1" "$BASE/users" | jq; }

# 取得單一使用者
get_user() { curl -s $HEADER "$BASE/users/$1" | jq; }

# 使用
get_users
create_user '{"name":"Bob"}'
get_user 1

3. 自動化測試

// 使用 fetch 寫 API 測試
async function testApi() {
  // 測試 GET
  const listRes = await fetch('/api/users');
  console.assert(listRes.status === 200, 'GET /users should return 200');

  // 測試 POST
  const createRes = await fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Test' }),
  });
  console.assert(createRes.status === 201, 'POST /users should return 201');

  const created = await createRes.json();
  console.assert(created.name === 'Test', 'Name should match');
}

常見問題

cURL 在 Windows 上引號不對?

Windows CMD 用雙引號,PowerShell 有轉義問題:

# PowerShell 中使用 cURL(其實是 Invoke-WebRequest 的別名)
# 使用 curl.exe 呼叫真正的 cURL
curl.exe -X POST https://api.example.com/users `
  -H "Content-Type: application/json" `
  -d '{\"name\": \"Alice\"}'

請求逾時怎麼排查?

1. DNS 解析慢?→ curl -w 查看 time_namelookup
2. 連線建立慢?→ curl -w 查看 time_connect
3. 伺服器處理慢?→ curl -w 查看 time_starttransfer - time_connect
4. 回應傳輸慢?→ curl -w 查看 time_total - time_starttransfer

總結

API 除錯是開發者的日常——掌握 cURL 指令、HTTP 狀態碼、認證方式和除錯技巧,能快速定位介面問題。工具庫的 cURL 轉程式工具 和 JSON 格式化工具 是 API 除錯的好搭檔,幫你快速測試介面和檢視回應。

#API testing#HTTP requests#cURL#API debugging#tutorial