📬 HTTP 方法
📖 定義
HTTP 方法是客戶端向伺服器表達想執行的動作。每個方法都有特定的意義和用途,是 RESTful API 設計的核心。
🎯 用比喻來理解
圖書館系統
GET = 查找書籍 (查詢)
├─ 詢問圖書管理員"這本書有嗎?"
├─ 僅取得資料
└─ 圖書館狀態不變
POST = 登記新書 (建立)
├─ 新增書籍到圖書館
├─ 圖書館狀態改變
└─ 建立新資源
PUT = 修改書籍資訊 (全面更新)
├─ 重新寫入書籍的所有資訊
└─ 全部替換
PATCH = 部分修改書籍資訊 (部分更新)
├─ 僅修改部分書籍資訊 (例如:借閱狀態)
└─ 僅變更部分內容
DELETE = 丟棄書籍 (刪除)
├─ 從圖書館移除書籍
└─ 刪除資源
💡 主要 HTTP 方法
GET - 查詢資料
用途: 從伺服器獲取資源
特點:
├─ 安全(Safe):不改變伺服器狀態
├─ 冪等(Idempotent):多次呼叫結果相同
├─ 可快取
└─ 出現在瀏覽器歷史中
請求範例:
GET /api/users HTTP/1.1
Host: example.com
// JavaScript fetch API
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data));
// jQuery
$.get('https://api.example.com/users', function(data) {
console.log(data);
});
// axios
axios.get('https://api.example.com/users')
.then(response => console.log(response.data));
# curl
curl https://api.example.com/users
# 查詢特定使用者
curl https://api.example.com/users/123
# 使用查詢參數
curl "https://api.example.com/users?page=1&limit=10"
回應範例:
HTTP/1.1 200 OK
Content-Type: application/json
{
"users": [
{ "id": 1, "name": "王小明" },
{ "id": 2, "name": "李大同" }
]
}