API 測試入門:用 Postman 和 pytest 打造你的第一個 API 測試
API 測試是現代 QA 必備技能。從 HTTP 基礎概念到實際用 Postman 和 pytest 寫測試,帶你踏出 API 測試的第一步。
Last Updated:2026-03-07
本文範例使用假設的 API 端點,實際測試時請替換為你的目標 API。
Table of Contents
1. 為什麼要學 API 測試?
比起 UI 測試,API 測試有幾個明顯優勢:
-
更快
不需要等頁面載入,直接測後端邏輯
-
更穩定
不受 UI 改版影響
-
更早測
前端還沒做好就能測後端
-
更容易自動化
純資料交換,不需要處理 UI 元素
2. HTTP 基礎快速複習
API 測試前,先搞懂 HTTP 方法:GET(取得資料)、POST(新增資料)、PUT/PATCH(更新資料)、DELETE(刪除資料)。常見的回應狀態碼:200 成功、201 建立成功、400 請求格式錯誤、401 未認證、403 沒有權限、404 找不到資源、500 伺服器錯誤。
3. 用 Postman 開始測試
Postman 是最友善的 API 測試工具:
-
建立 Collection
把相關 API 分組管理
-
設定環境變數
dev / staging / production 切換
-
寫測試腳本
在 Tests tab 用 JavaScript 驗證回應
-
用 Runner 批次執行
一次跑完所有測試案例
4. 用 pytest 寫 API 測試
當你需要更強大的自動化能力時,用 Python + pytest + requests。可以測試 GET 取得資料、POST 建立資料、以及各種錯誤處理場景。pytest 的 assert 語法直覺好讀,搭配 parametrize 可以輕鬆測試多組資料。
5. API 測試檢查清單
確保你的 API 測試涵蓋以下面向:
-
狀態碼驗證
確認回應的 HTTP 狀態碼正確
-
回應格式
JSON schema 是否符合規格
-
欄位驗證
必要欄位是否存在、資料型別是否正確
-
錯誤處理
是否回傳有意義的錯誤訊息
-
認證授權
認證和授權機制是否正常
-
效能
回應時間是否在可接受範圍內
Related Quick Guides
2026 QA 趨勢:AI 測試、Shift-Left 與職涯新方向
探索 QA 領域的最新趨勢,包含 AI 輔助測試、Shift-Left 策略、以及 QA 工程師的職涯轉型方向。
Beginner’s Guide to Performance Testing: A Complete Tutorial from Load Testing to Stress Testing
A Complete Guide to Getting Started with Performance Testing - Covers load testing, stress testing, and soak testing, introduces the practical usage of the three major tools JMeter, k6, and Locust, and learns to identify system bottlenecks from scratch to ensure online stability.
Bug 回報的藝術:讓開發者秒懂的 Bug Report 寫法
一份好的 Bug Report 能大幅加速修復速度。分享 Bug 回報的最佳實踐,包含模板、嚴重度分級、以及如何與開發有效溝通。
General Disclaimer
The information provided on this site is for reference only. We do not guarantee its completeness or accuracy. Users should determine the applicability of the information on their own.