MBE API 文档完善指南

本文档说明如何完善 MBE API 的 OpenAPI/Swagger 文档。

概述

MBE API 使用 FastAPI 框架,自动生成 OpenAPI 3.0 规范的文档。文档访问地址:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • OpenAPI JSON: http://localhost:8000/openapi.json

已完成的改进

1. OpenAPI 配置 (api/openapi_config.py)

  • ✅ 详细的API描述和介绍
  • ✅ 错误码说明表格
  • ✅ 认证方案说明
  • ✅ 速率限制说明
  • ✅ 服务器环境配置(生产/开发/本地)
  • ✅ 通用错误响应模型
  • ✅ 标签分组和描述

2. 通用模型 (api/models.py)

  • SuccessResponse - 成功响应模型
  • ErrorResponse - 错误响应模型
  • PaginationParams - 分页参数
  • PaginatedResponse - 分页响应
  • HealthResponse - 健康检查响应
  • LoginRequest / RegisterRequest - 认证请求
  • TokenResponse - Token响应
  • ChatRequest / ChatResponse - 聊天请求/响应
  • ChatMessage - 聊天消息模型

3. 健康检查API文档

  • /api/health - 基础健康检查(已完善文档)
  • /api/health/detailed - 详细健康检查(已完善文档)

如何为API端点添加文档

基本示例

from fastapi import APIRouter, Depends
from api.models import ChatRequest, ChatResponse, ErrorResponse

router = APIRouter(tags=["Chat"])

@router.post(
    "/chat",
    response_model=ChatResponse,
    summary="发送聊天消息",
    description="""
    向AI专家发送聊天消息并获取回答。
    
    **功能**:
    - 自动路由到合适的专家
    - 支持对话上下文
    - 返回置信度和来源信息
    
    **认证**: 需要API Key或Bearer Token
    """,
    responses={
        200: {
            "description": "成功响应",
            "content": {
                "application/json": {
                    "example": {
                        "answer": "根据您的问题...",
                        "expert_id": "civil_lawyer",
                        "confidence": 0.92,
                        "response_time_ms": 1250
                    }
                }
            }
        },
        400: {"$ref": "#/components/responses/400"},
        401: {"$ref": "#/components/responses/401"},
        429: {"$ref": "#/components/responses/429"},
        500: {"$ref": "#/components/responses/500"}
    }
)
async def chat(request: ChatRequest):
    """发送聊天消息"""
    # 实现代码
    pass

使用响应模型

from api.models import SuccessResponse, PaginatedResponse

@router.get(
    "/users",
    response_model=PaginatedResponse,
    summary="获取用户列表",
    description="分页查询用户列表"
)
async def list_users(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量")
):
    """获取用户列表"""
    pass

添加请求示例

class CreateExpertRequest(BaseModel):
    """创建专家请求"""
    name: str = Field(..., description="专家名称")
    description: str = Field(..., description="专家描述")
    
    class Config:
        json_schema_extra = {
            "example": {
                "name": "法律顾问专家",
                "description": "专注于法律咨询的AI专家"
            }
        }

待完善的API端点

高优先级

  1. 用户认证API (/api/v1/users)

    • POST /api/v1/users/register - 用户注册
    • POST /api/v1/users/login - 用户登录
    • POST /api/v1/users/refresh - 刷新Token
    • GET /api/v1/users/me - 获取当前用户信息
  2. 聊天API (/api/chat)

    • POST /api/chat/message - 发送消息
    • GET /api/chat/history - 获取历史记录
  3. 知识库API (/admin/knowledge)

    • GET /admin/knowledge/list - 获取知识库列表
    • POST /admin/knowledge/create - 创建知识库
    • POST /admin/knowledge/{kb_id}/upload - 上传文档

中优先级

  1. 专家市场API (/api/market)

    • GET /api/market/experts - 浏览专家
    • POST /api/market/experts/{expert_id}/invoke - 调用专家
  2. 训练管理API (/admin/training)

    • POST /admin/training/jobs - 创建训练任务
    • GET /admin/training/jobs/{job_id} - 查询训练状态
  3. 评估API (/api/evaluation)

    • POST /api/evaluation/knowledge-base - 评估知识库
    • POST /api/evaluation/expert - 评估专家

最佳实践

1. 使用描述性字段

class RequestModel(BaseModel):
    field: str = Field(
        ...,
        description="字段的详细说明",
        example="示例值",
        min_length=1,
        max_length=100
    )

2. 添加响应示例

responses={
    200: {
        "description": "成功",
        "content": {
            "application/json": {
                "example": {
                    "success": True,
                    "data": {}
                }
            }
        }
    }
}

3. 使用标签分组

router = APIRouter(tags=["Chat"])

4. 添加认证要求

@router.post(
    "/endpoint",
    dependencies=[Depends(require_auth)]  # 如果需要认证
)

5. 错误响应标准化

使用预定义的错误响应:

  • 400 - 请求参数错误
  • 401 - 未认证
  • 403 - 权限不足
  • 429 - 速率限制
  • 500 - 服务器错误

验证文档

启动服务后,访问以下地址验证文档:

  1. Swagger UI: http://localhost:8000/docs

    • 交互式API文档
    • 可以直接测试API
  2. ReDoc: http://localhost:8000/redoc

    • 更美观的文档展示
    • 适合阅读
  3. OpenAPI JSON: http://localhost:8000/openapi.json

    • 原始OpenAPI规范
    • 可用于生成SDK

下一步计划

  1. ✅ 完善健康检查API文档
  2. ⏳ 完善用户认证API文档
  3. ⏳ 完善聊天API文档
  4. ⏳ 完善知识库API文档
  5. ⏳ 创建API使用示例代码
  6. ⏳ 创建SDK文档

参考资源