dramaling-vocab-learning/backend/DramaLing.Api/API_DOCUMENTATION.md

19 KiB
Raw Permalink Blame History

DramaLing API 文檔

API 概覽

DramaLing API 是一個詞彙學習平台的後端服務,提供 AI 智能分析、音頻合成、用戶認證、詞卡管理、統計分析等功能。

基礎資訊:

  • 基礎URL: https://api.dramaling.com (production) / http://localhost:5000 (development)
  • API版本: v1
  • 資料格式: JSON
  • 字符編碼: UTF-8

認證說明

JWT Token 認證

大部分 API 端點需要 JWT Token 認證,除了標示 [AllowAnonymous] 的端點。

認證方式:

Authorization: Bearer {JWT_TOKEN}

Token 獲取: 透過 /api/auth/login/api/auth/register 端點獲取 JWT Token。

Token 有效期: 7天

錯誤處理

標準錯誤格式

{
  "Success": false,
  "Error": "錯誤訊息",
  "Details": "詳細錯誤資訊",
  "Timestamp": "2023-10-15T10:30:00Z"
}

HTTP 狀態碼

  • 200 OK - 請求成功
  • 400 Bad Request - 請求參數錯誤
  • 401 Unauthorized - 未授權或Token無效
  • 404 Not Found - 資源不存在
  • 500 Internal Server Error - 伺服器內部錯誤

1. AI Controller

路由: /api/ai 認證: 不需要

1.1 智能分析英文句子

端點: POST /api/ai/analyze-sentence 功能: 分析英文句子的語法、詞彙等資訊

請求體:

{
  "InputText": "The beautiful girl is reading a book.",
  "Options": {
    "IncludeGrammar": true,
    "IncludeVocabulary": true,
    "DetailLevel": "detailed"
  }
}

回應:

{
  "Success": true,
  "ProcessingTime": 1.23,
  "Data": {
    "Analysis": {
      "Grammar": [],
      "Vocabulary": [],
      "Complexity": "B1"
    },
    "Metadata": {
      "ProcessingDate": "2023-10-15T10:30:00Z"
    }
  }
}

1.2 健康檢查

端點: GET /api/ai/health 功能: 檢查 AI 服務狀態

回應:

{
  "Status": "Healthy",
  "Service": "AI Analysis Service",
  "Timestamp": "2023-10-15T10:30:00Z",
  "Version": "1.0"
}

1.3 分析統計資訊

端點: GET /api/ai/stats 功能: 獲取 AI 分析服務的統計資訊

回應:

{
  "Success": true,
  "Data": {
    "TotalAnalyses": 1000,
    "CachedAnalyses": 800,
    "CacheHitRate": 0.8,
    "AverageResponseTimeMs": 150,
    "LastAnalysisAt": "2023-10-15T10:30:00Z"
  }
}

2. Audio Controller

路由: /api/audio 認證: 需要

2.1 文字轉語音

端點: POST /api/audio/tts 功能: 將文字轉換為語音

請求體:

{
  "Text": "Hello, how are you?",
  "Accent": "us",
  "Speed": 1.0,
  "Voice": "en-US-AriaNeural"
}

回應:

{
  "AudioUrl": "https://storage.dramaling.com/audio/abc123.mp3",
  "Duration": 2.5,
  "CacheHash": "abc123def456"
}

參數說明:

  • Text: 要轉換的文字 (最大1000字符)
  • Accent: 口音 ("us" 或 "uk")
  • Speed: 播放速度 (0.5 - 2.0)
  • Voice: 語音ID (可選)

2.2 獲取快取音頻

端點: GET /api/audio/tts/cache/{hash} 功能: 根據快取雜湊值獲取已快取的音頻

回應:

{
  "AudioUrl": "https://storage.dramaling.com/audio/abc123.mp3",
  "Duration": 2.5
}

2.3 發音評估

端點: POST /api/audio/pronunciation/evaluate 功能: 評估用戶發音品質

請求 (multipart/form-data):

  • audioFile: 音頻檔案 (最大10MB, 支援 WAV/MP3/OGG)
  • targetText: 目標文字
  • userLevel: 用戶等級 (預設 "B1")

回應:

{
  "OverallScore": 85,
  "AccuracyScore": 88,
  "FluencyScore": 82,
  "ProsodicScore": 85,
  "WordScores": [
    {
      "Word": "hello",
      "Score": 90,
      "Feedback": "Excellent pronunciation"
    }
  ]
}

2.4 獲取支援語音列表

端點: GET /api/audio/voices 功能: 獲取可用的 TTS 語音列表

回應:

{
  "US": [
    {
      "Id": "en-US-AriaNeural",
      "Name": "Aria",
      "Gender": "Female"
    }
  ],
  "UK": [
    {
      "Id": "en-GB-SoniaNeural",
      "Name": "Sonia",
      "Gender": "Female"
    }
  ]
}

3. Auth Controller

路由: /api/auth 認證: 混合 (部分端點需要認證)

3.1 用戶註冊

端點: POST /api/auth/register 認證: 不需要

請求體:

{
  "Username": "john_doe",
  "Email": "john@example.com",
  "Password": "securePassword123"
}

回應:

{
  "Success": true,
  "Data": {
    "Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "User": {
      "Id": "123e4567-e89b-12d3-a456-426614174000",
      "Username": "john_doe",
      "Email": "john@example.com",
      "DisplayName": "john_doe",
      "AvatarUrl": null,
      "SubscriptionType": "free"
    }
  }
}

驗證規則:

  • Username: 3-50字符
  • Email: 有效的電子郵件格式
  • Password: 至少8字符

3.2 用戶登入

端點: POST /api/auth/login 認證: 不需要

請求體:

{
  "Email": "john@example.com",
  "Password": "securePassword123"
}

回應: 與註冊相同格式

3.3 獲取用戶資料

端點: GET /api/auth/profile 認證: 需要

回應:

{
  "Success": true,
  "Data": {
    "Id": "123e4567-e89b-12d3-a456-426614174000",
    "Email": "john@example.com",
    "DisplayName": "John Doe",
    "AvatarUrl": "https://example.com/avatar.jpg",
    "SubscriptionType": "premium",
    "CreatedAt": "2023-10-15T10:30:00Z"
  }
}

3.4 更新用戶資料

端點: PUT /api/auth/profile 認證: 需要

請求體:

{
  "DisplayName": "John Smith",
  "AvatarUrl": "https://example.com/new-avatar.jpg",
  "Preferences": {
    "theme": "dark",
    "language": "zh-TW"
  }
}

3.5 獲取用戶設定

端點: GET /api/auth/settings 認證: 需要

回應:

{
  "Success": true,
  "Data": {
    "DailyGoal": 20,
    "ReminderTime": "09:00:00",
    "ReminderEnabled": true,
    "DifficultyPreference": "balanced",
    "AutoPlayAudio": true,
    "ShowPronunciation": true
  }
}

3.6 更新用戶設定

端點: PUT /api/auth/settings 認證: 需要

請求體:

{
  "DailyGoal": 25,
  "ReminderTime": "08:30:00",
  "ReminderEnabled": false,
  "DifficultyPreference": "aggressive",
  "AutoPlayAudio": false,
  "ShowPronunciation": true
}

設定選項:

  • DailyGoal: 1-100
  • DifficultyPreference: "conservative", "balanced", "aggressive"

3.7 檢查認證狀態

端點: GET /api/auth/status 認證: 需要

回應:

{
  "Success": true,
  "Data": {
    "IsAuthenticated": true,
    "UserId": "123e4567-e89b-12d3-a456-426614174000",
    "Timestamp": "2023-10-15T10:30:00Z"
  }
}

4. Image Generation Controller

路由: /api/imagegeneration 認證: 不需要 (暫時)

4.1 為詞卡生成圖片

端點: POST /api/imagegeneration/flashcards/{flashcardId}/generate 功能: 為指定詞卡生成例句圖片

路徑參數:

  • flashcardId: 詞卡ID (GUID)

請求體:

{
  "Style": "realistic",
  "Quality": "high",
  "Size": "1024x1024"
}

回應:

{
  "success": true,
  "data": {
    "RequestId": "789e0123-e45f-67g8-h901-234567890abc",
    "Status": "pending",
    "EstimatedTime": 30
  }
}

4.2 獲取生成狀態

端點: GET /api/imagegeneration/requests/{requestId}/status 功能: 獲取圖片生成請求的狀態

回應:

{
  "success": true,
  "data": {
    "RequestId": "789e0123-e45f-67g8-h901-234567890abc",
    "Status": "completed",
    "Progress": 100,
    "ImageUrl": "https://storage.dramaling.com/images/generated/abc123.jpg",
    "CreatedAt": "2023-10-15T10:30:00Z"
  }
}

狀態值:

  • pending: 等待中
  • processing: 處理中
  • completed: 已完成
  • failed: 失敗
  • cancelled: 已取消

4.3 取消生成請求

端點: POST /api/imagegeneration/requests/{requestId}/cancel 功能: 取消圖片生成請求

回應:

{
  "success": true,
  "message": "Generation cancelled successfully"
}

4.4 獲取生成歷史

端點: GET /api/imagegeneration/history 功能: 獲取用戶的圖片生成歷史

查詢參數:

  • page: 頁碼 (預設: 1)
  • pageSize: 每頁數量 (預設: 20)

回應:

{
  "success": true,
  "data": {
    "requests": [],
    "pagination": {
      "currentPage": 1,
      "pageSize": 20,
      "totalCount": 0,
      "totalPages": 0
    }
  }
}

5. Options Vocabulary Test Controller

路由: /api/test/optionsvocabularytest 認證: 不需要 功能: 測試和開發用的詞彙選項生成服務

5.1 測試干擾選項生成

端點: GET /api/test/optionsvocabularytest/generate-distractors 功能: 測試為目標詞彙生成干擾選項

查詢參數:

  • targetWord: 目標詞彙 (預設: "beautiful")
  • cefrLevel: CEFR等級 (預設: "B1")
  • partOfSpeech: 詞性 (預設: "adjective")
  • count: 生成數量 (預設: 3)

回應:

{
  "success": true,
  "targetWord": "beautiful",
  "cefrLevel": "B1",
  "partOfSpeech": "adjective",
  "requestedCount": 3,
  "actualCount": 3,
  "distractors": ["pretty", "lovely", "attractive"]
}

5.2 測試詞彙庫充足性

端點: GET /api/test/optionsvocabularytest/check-sufficiency 功能: 檢查特定等級和詞性的詞彙庫是否充足

查詢參數:

  • cefrLevel: CEFR等級 (預設: "B1")
  • partOfSpeech: 詞性 (預設: "adjective")

回應:

{
  "success": true,
  "cefrLevel": "B1",
  "partOfSpeech": "adjective",
  "hasSufficientVocabulary": true
}

5.3 測試詳細干擾選項生成

端點: GET /api/test/optionsvocabularytest/generate-distractors-detailed 功能: 生成帶詳細資訊的干擾選項

回應:

{
  "success": true,
  "targetWord": "beautiful",
  "cefrLevel": "B1",
  "partOfSpeech": "adjective",
  "requestedCount": 3,
  "actualCount": 3,
  "distractors": [
    {
      "Word": "pretty",
      "CEFRLevel": "A2",
      "PartOfSpeech": "adjective",
      "WordLength": 6,
      "IsActive": true
    }
  ]
}

5.4 測試詞彙庫覆蓋率

端點: GET /api/test/optionsvocabularytest/coverage-test 功能: 測試多種詞性和等級的詞彙庫覆蓋率

回應:

{
  "success": true,
  "coverageResults": [
    {
      "cefrLevel": "A1",
      "partOfSpeech": "noun",
      "hasSufficientVocabulary": true,
      "generatedCount": 3,
      "sampleDistractors": ["cat", "dog", "book"]
    }
  ]
}

6. Stats Controller

路由: /api/stats 認證: 需要

6.1 獲取儀表板統計

端點: GET /api/stats/dashboard 功能: 獲取用戶學習儀表板的統計資料

回應:

{
  "Success": true,
  "Data": {
    "TotalWords": 150,
    "WordsToday": 12,
    "StreakDays": 7,
    "AccuracyPercentage": 85,
    "TodayReviewCount": 23,
    "CompletedToday": 12,
    "RecentWords": [
      {
        "Word": "negotiate",
        "Translation": "協商",
        "Status": "learned"
      }
    ],
    "CardSets": []
  }
}

6.2 獲取學習趨勢

端點: GET /api/stats/trends 功能: 獲取指定時期的學習趨勢資料

查詢參數:

  • period: 時期 ("week", "month", "year", 預設: "week")

回應:

{
  "Success": true,
  "Data": {
    "Period": "week",
    "DateRange": {
      "Start": "2023-10-09",
      "End": "2023-10-15"
    },
    "DailyCounts": [
      {
        "Date": "2023-10-09",
        "WordsStudied": 15,
        "WordsCorrect": 12,
        "StudyTimeSeconds": 1800,
        "SessionCount": 3,
        "CardsGenerated": 5,
        "Accuracy": 80
      }
    ],
    "Summary": {
      "TotalWordsStudied": 105,
      "TotalCorrect": 89,
      "TotalStudyTimeSeconds": 12600,
      "TotalSessions": 21,
      "AverageAccuracy": 85,
      "AverageDailyWords": 15,
      "AverageSessionDuration": 600
    }
  }
}

6.3 獲取詳細統計

端點: GET /api/stats/detailed 功能: 獲取詳細的學習統計分析

回應:

{
  "Success": true,
  "Data": {
    "ByDifficulty": {
      "A1": 30,
      "A2": 45,
      "B1": 50,
      "B2": 25
    },
    "ByPartOfSpeech": {
      "noun": 60,
      "verb": 40,
      "adjective": 35,
      "adverb": 15
    },
    "MasteryDistribution": {
      "Mastered": 80,
      "Learning": 60,
      "New": 10
    },
    "LearningCurve": [
      {
        "Date": "2023-10-01",
        "Accuracy": 75,
        "Count": 8
      }
    ],
    "Summary": {
      "TotalCards": 150,
      "AverageMastery": 53,
      "OverallAccuracy": 85
    }
  }
}

7. Flashcards Controller

路由: /api/flashcards 認證: 不需要 (暫時)

7.1 獲取詞卡列表

端點: GET /api/flashcards 功能: 獲取用戶的詞卡列表

查詢參數:

  • search: 搜尋關鍵詞 (可選)
  • favoritesOnly: 僅顯示收藏 (預設: false)

回應:

{
  "Success": true,
  "Data": {
    "Flashcards": [
      {
        "Id": "123e4567-e89b-12d3-a456-426614174000",
        "Word": "beautiful",
        "Translation": "美麗的",
        "Definition": "having beauty; pleasing to the senses",
        "PartOfSpeech": "adjective",
        "Pronunciation": "/ˈbjuːtɪf(ə)l/",
        "Example": "She has a beautiful smile.",
        "ExampleTranslation": "她有美麗的笑容。",
        "IsFavorite": true,
        "DifficultyLevel": "A2",
        "CreatedAt": "2023-10-15T10:30:00Z",
        "UpdatedAt": "2023-10-15T10:30:00Z"
      }
    ],
    "Count": 1
  }
}

7.2 創建詞卡

端點: POST /api/flashcards 功能: 創建新的詞卡

請求體:

{
  "Word": "beautiful",
  "Translation": "美麗的",
  "Definition": "having beauty; pleasing to the senses",
  "PartOfSpeech": "adjective",
  "Pronunciation": "/ˈbjuːtɪf(ə)l/",
  "Example": "She has a beautiful smile.",
  "ExampleTranslation": "她有美麗的笑容。"
}

回應:

{
  "Success": true,
  "Data": {
    "Id": "123e4567-e89b-12d3-a456-426614174000",
    "Word": "beautiful",
    "Translation": "美麗的",
    "DifficultyLevel": "A2",
    "CreatedAt": "2023-10-15T10:30:00Z"
  },
  "Message": "詞卡創建成功"
}

7.3 獲取單個詞卡

端點: GET /api/flashcards/{id} 功能: 獲取特定詞卡的詳細資訊

回應:

{
  "Success": true,
  "Data": {
    "Id": "123e4567-e89b-12d3-a456-426614174000",
    "Word": "beautiful",
    "Translation": "美麗的",
    "Definition": "having beauty; pleasing to the senses",
    "PartOfSpeech": "adjective",
    "Pronunciation": "/ˈbjuːtɪf(ə)l/",
    "Example": "She has a beautiful smile.",
    "ExampleTranslation": "她有美麗的笑容。",
    "IsFavorite": true,
    "DifficultyLevel": "A2",
    "CreatedAt": "2023-10-15T10:30:00Z",
    "UpdatedAt": "2023-10-15T10:30:00Z"
  }
}

7.4 更新詞卡

端點: PUT /api/flashcards/{id} 功能: 更新特定詞卡的資訊

請求體: 與創建詞卡相同格式

回應:

{
  "Success": true,
  "Data": {
    "Id": "123e4567-e89b-12d3-a456-426614174000",
    "Word": "beautiful",
    "Translation": "美麗的",
    "UpdatedAt": "2023-10-15T10:30:00Z"
  },
  "Message": "詞卡更新成功"
}

7.5 刪除詞卡

端點: DELETE /api/flashcards/{id} 功能: 刪除特定詞卡

回應:

{
  "Success": true,
  "Message": "詞卡已刪除"
}

7.6 切換收藏狀態

端點: POST /api/flashcards/{id}/favorite 功能: 切換詞卡的收藏狀態

回應:

{
  "Success": true,
  "IsFavorite": true,
  "Message": "已加入收藏"
}

請求/回應範例

完整的詞卡創建流程

1. 創建詞卡

curl -X POST "https://api.dramaling.com/api/flashcards" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "Word": "accomplish",
    "Translation": "完成",
    "Definition": "to finish something successfully",
    "PartOfSpeech": "verb",
    "Pronunciation": "/əˈkʌmplɪʃ/",
    "Example": "She accomplished her goal.",
    "ExampleTranslation": "她完成了目標。"
  }'

2. 為詞卡生成圖片

curl -X POST "https://api.dramaling.com/api/imagegeneration/flashcards/{flashcard_id}/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "Style": "realistic",
    "Quality": "high",
    "Size": "1024x1024"
  }'

3. 生成音頻

curl -X POST "https://api.dramaling.com/api/audio/tts" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "Text": "She accomplished her goal.",
    "Accent": "us",
    "Speed": 1.0
  }'

用戶註冊和認證流程

1. 註冊新用戶

curl -X POST "https://api.dramaling.com/api/auth/register" \
  -H "Content-Type: application/json" \
  -d '{
    "Username": "john_doe",
    "Email": "john@example.com",
    "Password": "securePassword123"
  }'

2. 登入獲取Token

curl -X POST "https://api.dramaling.com/api/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "Email": "john@example.com",
    "Password": "securePassword123"
  }'

3. 使用Token獲取用戶資料

curl -X GET "https://api.dramaling.com/api/auth/profile" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

開發注意事項

暫時的設定

  • FlashcardsController 和 ImageGenerationController 目前設為 [AllowAnonymous] 用於開發測試
  • 使用固定的測試用戶ID: 00000000-0000-0000-0000-000000000001
  • 部分統計資料使用模擬數據

生產環境配置

  • 需要設定正確的 JWT Secret 環境變數
  • 需要配置 Azure Speech Service
  • 需要設定檔案存儲服務

API 版本控制

目前所有 API 都在 v1 版本,未來新功能將透過版本控制進行管理。

錯誤處理最佳實踐

  • 始終檢查 Success 欄位
  • 根據HTTP狀態碼處理不同錯誤類型
  • 實現適當的重試機制
  • 記錄和監控API錯誤

文檔版本: 1.0 最後更新: 2023-10-15 聯絡資訊: api-support@dramaling.com