什麼是 RESTful API?
REST(Representational State Transfer)是一種軟體架構風格,用於設計網路服務。RESTful API 遵循 REST 原則,提供一致且直觀的方式來操作資源。
核心原則核心原則
統一介面(Uniform Interface)
所有資源都通過統一的介面進行操作,使用標準的 HTTP 方法。
無狀態(Stateless)
每個請求都包含處理該請求所需的所有資訊,伺服器不保存客戶端狀態。
可快取(Cacheable)
回應應該明確標示是否可以快取,以提高效能。
分層系統(Layered System)
客戶端無法判斷是直接連接到終端伺服器,還是連接到中間層。
HTTP 方法對應
HTTP 方法 | 用途 | 範例 URL | 說明 |
GET | 讀取資源 | GET /users | 獲取所有用戶 |
GET | 讀取單一資源 | GET /users/123 | 獲取 ID 為 123 的用戶 |
POST | 創建資源 | POST /users | 創建新用戶 |
PUT | 完整更新資源 | PUT /users/123 | 完整更新用戶 123 |
PATCH | 部分更新資源 | PATCH /users/123 | 部分更新用戶 123 |
DELETE | 刪除資源 | DELETE /users/123 | 刪除用戶 123 |
URL 設計規範
使用名詞,不用動詞
✅ 正確:GET /users
❌ 錯誤:GET /getUsers
使用複數形式
✅ 正確:/users, /products, /orders
❌ 錯誤:/user, /product, /order
階層關係表示
GET /users/123/orders # 獲取用戶 123 的所有訂單
GET /users/123/orders/456 # 獲取用戶 123 的訂單 456
查詢參數用於篩選和分頁
GET /users?page=2&limit=10&status=active
GET /products?category=electronics&sort=price&order=desc
HTTP 狀態碼
成功回應 (2xx)
- 200 OK – 請求成功
- 201 Created – 資源創建成功
- 204 No Content – 請求成功但無回應內容(通常用於 DELETE)
客戶端錯誤 (4xx)
- 400 Bad Request – 請求語法錯誤
- 401 Unauthorized – 需要驗證
- 403 Forbidden – 禁止訪問
- 404 Not Found – 資源不存在
- 405 Method Not Allowed – HTTP 方法不被允許
- 422 Unprocessable Entity – 請求格式正確但語義錯誤
伺服器錯誤 (5xx)
- 500 Internal Server Error – 伺服器內部錯誤
- 502 Bad Gateway – 網關錯誤
- 503 Service Unavailable – 服務暫時無法使用
回應格式規範
成功回應範例
{
"success": true,
"data": {
"id": 123,
"name": "John Doe",
"email": "john@example.com"
},
"message": "User retrieved successfully"
}
錯誤回應範例
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Email is required",
"details": {
"field": "email",
"value": null
}
}
}
列表回應範例
{
"success": true,
"data": [
{"id": 1, "name": "User 1"},
{"id": 2, "name": "User 2"}
],
"pagination": {
"current_page": 1,
"per_page": 10,
"total": 100,
"total_pages": 10
}
}
版本控制
URL 路徑版本控制
GET /v1/users
GET /v2/users
Header 版本控制
GET /users
Accept: application/vnd.api+json;version=1
認證與授權
Bearer Token
Authorization: Bearer your_access_token_here
API Key
X-API-Key: your_api_key_here
最佳實踐
使用 HTTPS
所有 API 端點都應該使用 HTTPS 來確保資料傳輸安全。
提供清楚的錯誤訊息
錯誤回應應該包含足夠的資訊讓開發者理解問題所在。
實作速率限制
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
使用適當的 Content-Type
Content-Type: application/json
Content-Type: application/xml
支援 CORS
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
常見 API 端點範例
# 用戶管理
GET /users # 獲取用戶列表
POST /users # 創建新用戶
GET /users/{id} # 獲取特定用戶
PUT /users/{id} # 更新用戶
DELETE /users/{id} # 刪除用戶
# 文章管理
GET /posts # 獲取文章列表
POST /posts # 創建新文章
GET /posts/{id} # 獲取特定文章
PUT /posts/{id} # 更新文章
DELETE /posts/{id} # 刪除文章
# 巢狀資源
GET /users/{id}/posts # 獲取用戶的文章
POST /users/{id}/posts # 為用戶創建文章
GET /posts/{id}/comments # 獲取文章的評論