ENGINEERING BRIDGE · 27
REST API:不是把動詞都塞進 URL,而是設計清楚的 Resource Contract
REST 不是只有「GET/POST/PUT/DELETE 對應 CRUD」。真正重要的是 resource identity、method semantics、status、representation、idempotency 與 error contract。
Learning outcomes
- 能把 API path 設計成 resource-oriented。
- 能區分 GET/POST/PUT/PATCH/DELETE 的基本語意。
- 能選擇合理 status code。
- 能解釋 idempotency 與 retry 的關係。
1. Resource
/courses
/courses/42
/users/7/coursesURL 主要表示資源;action 由 HTTP method 表達。
2. Method Semantics
GET /courses
POST /courses
GET /courses/42
PATCH /courses/42
DELETE /courses/42GET 應讀取;POST 常建立新資源或非 idempotent action;PUT/PATCH 更新;DELETE 移除。
3. Status Code
200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict
500 Internal Server ErrorStatus 是 machine-readable contract,不要所有錯誤都回 200 再把 error 塞 body。
4. Error Shape
{
"error": "validation_failed",
"message": "score must be 0-100",
"requestId": "abc123"
}一致 error shape 能讓 client 和 logs 更容易追蹤。
5. Idempotency
GET/PUT/DELETE 的設計通常應具備 idempotent 語意:同一 request 重複執行,目標最終狀態一致。POST 若有 side effect,retry 可能需要 idempotency key。
Project checkpoint:Course API Contract
GET /courses
→ 200 Course[]
POST /courses
→ 201 Course
→ 400 validation
→ 401 no auth
PATCH /courses/:id
→ 200 Course
→ 403 forbidden
→ 404 missingDebug evidence:Client 說「API 壞了」
先看 method/path/status/body。若 client 用 POST /courses/42 但 server contract 是 PATCH /courses/42,這是 interface mismatch,不是 database 壞掉。
Knowledge check
- Resource-oriented URL 和 action-oriented URL 差在哪?
- 401/403/404 各代表什麼?
- 什麼是 idempotency?
- 替 Courses 設計一組 CRUD endpoints。