dramaling-app/docs/02_design/function-specs/common/api-specifications.md

568 lines
11 KiB
Markdown

# 共同API規格
## 📋 概述
**文檔名稱**: 跨平台API規格定義
**建立日期**: 2025-09-09
**適用平台**: Mobile App / Web App
**API版本**: v1
**基礎URL**: `https://api.dramaling.com/api/v1`
本文檔定義了Drama Ling系統中所有平台通用的API接口規格。
## 🔧 通用設計原則
### RESTful 設計
- 使用標準HTTP方法 (GET, POST, PUT, DELETE)
- 資源導向的URL設計
- 統一的狀態碼使用
- JSON格式的請求和回應
### 認證機制
- JWT Bearer Token認證
- 訪問令牌有效期: 1小時
- 刷新令牌有效期: 30天
- 自動令牌刷新機制
### 錯誤處理
- 統一的錯誤回應格式
- 多語言錯誤訊息支援
- 詳細的錯誤碼系統
### 回應格式
```typescript
interface APIResponse<T> {
success: boolean;
data?: T;
error?: APIError;
message: string;
meta: {
timestamp: string;
requestId: string;
version: string;
};
}
interface APIError {
code: string;
message: string;
details?: any;
}
```
## 🔐 認證相關API
### 用戶註冊
```http
POST /auth/register
Content-Type: application/json
{
"email": "user@example.com",
"password": "securePassword123",
"username": "learner123",
"nativeLanguage": "zh-TW",
"learningLanguages": ["en"]
}
```
**回應**:
```typescript
interface RegisterResponse {
userId: string;
username: string;
email: string;
accessToken: string;
refreshToken: string;
expiresIn: number;
userRole: string;
}
```
### 用戶登入
```http
POST /auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "securePassword123",
"platform": "mobile" | "web",
"rememberMe": boolean
}
```
### Token刷新
```http
POST /auth/refresh
Authorization: Bearer <refresh_token>
```
### 第三方登入
```http
POST /auth/social
Content-Type: application/json
{
"provider": "google" | "apple" | "facebook",
"token": "social_provider_token",
"platform": "mobile" | "web"
}
```
## 👤 用戶資料API
### 獲取用戶資料
```http
GET /users/profile
Authorization: Bearer <access_token>
```
### 更新用戶資料
```http
PUT /users/profile
Authorization: Bearer <access_token>
Content-Type: application/json
{
"username": "newUsername",
"nativeLanguage": "zh-TW",
"learningLanguages": ["en", "ja"],
"profile": {
"firstName": "John",
"lastName": "Doe",
"bio": "Language learning enthusiast"
}
}
```
### 獲取學習進度
```http
GET /users/progress
Authorization: Bearer <access_token>
Query Parameters:
- skill: string (optional) - vocabulary|dialogue|pronunciation
- timeframe: string (optional) - day|week|month|all
```
**回應**:
```typescript
interface ProgressResponse {
overallProgress: number;
skillProgress: {
vocabulary: SkillProgress;
dialogue: SkillProgress;
pronunciation: SkillProgress;
};
recentAchievements: Achievement[];
nextGoals: Goal[];
}
```
### 獲取遊戲統計
```http
GET /users/game-stats
Authorization: Bearer <access_token>
```
## 📚 學習內容API
### 獲取詞彙列表
```http
GET /vocabulary
Authorization: Bearer <access_token>
Query Parameters:
- language: string (required) - 語言代碼
- level: number (optional) - 難度等級 1-5
- category: string (optional) - 詞彙分類
- limit: number (optional) - 返回數量限制
- offset: number (optional) - 偏移量
```
### 獲取詞彙詳情
```http
GET /vocabulary/{vocabularyId}
Authorization: Bearer <access_token>
```
**回應**:
```typescript
interface VocabularyDetail {
id: string;
word: string;
pronunciation: string;
definitions: Definition[];
examples: Example[];
audioUrl: string;
relatedWords: RelatedWord[];
userProgress?: {
masteryLevel: number;
lastStudied: string;
studyCount: number;
};
}
```
### 獲取對話列表
```http
GET /dialogues
Authorization: Bearer <access_token>
Query Parameters:
- difficulty: number (optional)
- scenario: string (optional)
- completed: boolean (optional)
```
### 獲取對話詳情
```http
GET /dialogues/{dialogueId}
Authorization: Bearer <access_token>
```
### 搜索學習內容
```http
GET /content/search
Authorization: Bearer <access_token>
Query Parameters:
- query: string (required) - 搜索關鍵詞
- type: string (optional) - vocabulary|dialogue|all
- language: string (required)
```
## 🎯 學習活動API
### 開始學習會話
```http
POST /learning/sessions
Authorization: Bearer <access_token>
Content-Type: application/json
{
"type": "vocabulary" | "dialogue" | "review",
"contentId": "content_uuid",
"settings": {
"difficulty": number,
"timeLimit": number,
"hints": boolean
}
}
```
**回應**:
```typescript
interface SessionResponse {
sessionId: string;
content: LearningContent;
questions: Question[];
timeLimit: number;
lifePointsCost: number;
}
```
### 提交答案
```http
POST /learning/sessions/{sessionId}/answers
Authorization: Bearer <access_token>
Content-Type: application/json
{
"questionId": "question_uuid",
"answer": any,
"responseTime": number,
"hintsUsed": number
}
```
**回應**:
```typescript
interface AnswerResponse {
correct: boolean;
correctAnswer?: any;
explanation?: string;
scoreGained: number;
lifePointsLost: number;
nextQuestion?: Question;
}
```
### 完成學習會話
```http
POST /learning/sessions/{sessionId}/complete
Authorization: Bearer <access_token>
```
**回應**:
```typescript
interface SessionCompleteResponse {
finalScore: number;
accuracy: number;
xpGained: number;
diamondsGained: number;
achievementsUnlocked: Achievement[];
nextRecommendations: Recommendation[];
}
```
### 獲取複習內容
```http
GET /learning/review
Authorization: Bearer <access_token>
Query Parameters:
- type: string (optional) - vocabulary|dialogue|all
- limit: number (optional)
```
## 🏆 遊戲化系統API
### 獲取成就列表
```http
GET /achievements
Authorization: Bearer <access_token>
Query Parameters:
- category: string (optional)
- completed: boolean (optional)
```
### 獲取用戶道具
```http
GET /inventory
Authorization: Bearer <access_token>
```
### 使用道具
```http
POST /inventory/use
Authorization: Bearer <access_token>
Content-Type: application/json
{
"itemId": "item_uuid",
"quantity": number,
"context": {
"sessionId": "session_uuid"
}
}
```
### 購買道具
```http
POST /store/purchase
Authorization: Bearer <access_token>
Content-Type: application/json
{
"itemId": "item_uuid",
"quantity": number,
"paymentMethod": "diamonds" | "learning_coins" | "real_money"
}
```
### 獲取排行榜
```http
GET /leaderboard
Authorization: Bearer <access_token>
Query Parameters:
- type: string - xp|vocabulary|dialogue|streak
- timeframe: string - day|week|month|all
- limit: number (optional)
```
## 📊 分析與報告API
### 獲取學習分析
```http
GET /analytics/learning
Authorization: Bearer <access_token>
Query Parameters:
- startDate: string (YYYY-MM-DD)
- endDate: string (YYYY-MM-DD)
- granularity: string - day|week|month
```
**回應**:
```typescript
interface LearningAnalytics {
timeRange: {
start: string;
end: string;
};
summary: {
totalStudyTime: number;
wordsLearned: number;
dialoguesCompleted: number;
overallAccuracy: number;
streakDays: number;
};
skillBreakdown: SkillAnalytics[];
progressTrend: DataPoint[];
weakAreas: WeakArea[];
recommendations: string[];
}
```
### 導出學習數據
```http
GET /analytics/export
Authorization: Bearer <access_token>
Query Parameters:
- format: string - json|csv|pdf
- startDate: string
- endDate: string
- includePersonal: boolean
```
## 🔄 實時功能API
### WebSocket連接 (適用於Web端)
```
WSS /ws/learning
Authorization: Bearer <access_token>
```
**支援事件**:
- `session_start` - 學習會話開始
- `question_answered` - 回答題目
- `achievement_unlocked` - 解鎖成就
- `life_point_restored` - 命條恢復
- `friend_activity` - 好友活動通知
### 推送通知API (適用於Mobile端)
```http
POST /notifications/register
Authorization: Bearer <access_token>
Content-Type: application/json
{
"deviceToken": "fcm_device_token",
"platform": "ios" | "android",
"preferences": {
"studyReminders": boolean,
"achievements": boolean,
"friends": boolean
}
}
```
## 🌐 多語言支援API
### 獲取語言包
```http
GET /localization/{languageCode}
Query Parameters:
- version: string (optional) - 語言包版本號
```
### 獲取支援語言列表
```http
GET /localization/languages
```
## 🛡️ 資料保護API
### 請求數據導出
```http
POST /privacy/export-request
Authorization: Bearer <access_token>
```
### 請求帳戶刪除
```http
POST /privacy/delete-request
Authorization: Bearer <access_token>
Content-Type: application/json
{
"reason": string,
"confirmPassword": string
}
```
### 更新隱私設定
```http
PUT /privacy/settings
Authorization: Bearer <access_token>
Content-Type: application/json
{
"dataCollection": boolean,
"analytics": boolean,
"marketing": boolean,
"thirdPartySharing": boolean
}
```
## 📈 API限流規則
### 頻率限制
| 端點類別 | 限制 | 時間窗口 |
|---------|------|----------|
| 認證相關 | 5次 | 每分鐘 |
| 學習內容 | 100次 | 每分鐘 |
| 學習活動 | 50次 | 每分鐘 |
| 分析報告 | 10次 | 每分鐘 |
| 通用查詢 | 200次 | 每分鐘 |
### 限流回應
```http
HTTP/1.1 429 Too Many Requests
Retry-After: 60
{
"success": false,
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Request rate limit exceeded"
}
}
```
## 🔍 錯誤碼參考
### 認證錯誤 (4xx)
- `INVALID_CREDENTIALS` (401) - 登入憑證錯誤
- `TOKEN_EXPIRED` (401) - Token已過期
- `TOKEN_INVALID` (401) - Token格式錯誤
- `INSUFFICIENT_PERMISSIONS` (403) - 權限不足
### 業務邏輯錯誤 (4xx)
- `INSUFFICIENT_LIFE_POINTS` (402) - 命條不足
- `CONTENT_NOT_FOUND` (404) - 學習內容不存在
- `SESSION_EXPIRED` (410) - 學習會話已過期
- `INVALID_ANSWER_FORMAT` (422) - 答案格式錯誤
### 系統錯誤 (5xx)
- `INTERNAL_SERVER_ERROR` (500) - 內部伺服器錯誤
- `DATABASE_ERROR` (503) - 資料庫連接錯誤
- `THIRD_PARTY_SERVICE_ERROR` (503) - 第三方服務錯誤
## 📋 API測試
### 測試端點
```
開發環境: https://dev-api.dramaling.com/api/v1
測試環境: https://test-api.dramaling.com/api/v1
生產環境: https://api.dramaling.com/api/v1
```
### 測試帳號
```
測試用戶: test@dramaling.com
測試密碼: TestUser123456
測試Token: 開發環境提供長效測試Token
```
### Postman Collection
- 完整API集合下載: `/docs/api/postman-collection.json`
- 環境變數設定: `/docs/api/postman-environment.json`
---
**文檔狀態**: 🟢 已完成
**最後更新**: 2025-09-09
**版本**: v1.0
**相關文檔**:
- `業務規則.md` - 業務邏輯規則
- `數據模型.md` - 數據結構定義
- `../mobile/` - 移動端功能規格
- `../web/` - Web端功能規格
- `/swagger-ui.html` - 互動式API文檔