返回笔记首页

API 接口文档

主题配置

API 概览

基础信息

  • Base URL: https://your-domain.com/api
  • 认证方式: Bearer Token(Supabase Auth)
  • 数据格式: JSON
  • 字符编码: UTF-8

认证

所有 API 请求都需要在 Header 中包含认证 token:

http
Authorization: Bearer YOUR_ACCESS_TOKEN

获取 Token

typescript
// 使用 Supabase 客户端登录
const { data, error } = await supabase.auth.signInWithPassword({
  email: 'user@example.com',
  password: 'password',
});

const token = data.session.access_token;

AI Agent 相关接口

1. 规划 Agent - 生成文章大纲

POST/api/ai/plan

生成结构化的文章大纲

请求参数

typescript
interface PlanRequest {
  topic: string;              // 文章主题(必填)
  type: string;               // 文章类型(blog, xiaohongshu, article, weixin)
  audience: string;           // 目标受众
  wordCount: number;          // 目标字数
  tone: string;               // 语气(professional, casual, humorous)
}

请求示例

typescript
const response = await fetch('/api/ai/plan', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
  },
  body: JSON.stringify({
    topic: 'AI 在前端开发中的应用',
    type: 'blog',
    audience: '前端开发者',
    wordCount: 2000,
    tone: 'professional',
  }),
});

const data = await response.json();

响应示例

json
{
  "success": true,
  "data": {
    "outline": {
      "title": "AI 赋能前端:开发效率提升指南",
      "introduction": {
        "hook": "你是否想过,AI 可以让你的开发效率提升 10 倍?",
        "thesis": "本文将探讨 AI 在前端开发中的实际应用",
        "wordCount": 200
      },
      "sections": [
        {
          "heading": "AI 代码生成工具",
          "points": [
            "GitHub Copilot 的使用技巧",
            "如何提高代码建议的准确性",
            "实际案例分析"
          ],
          "wordCount": 500,
          "tips": "提供具体的代码示例"
        }
      ],
      "conclusion": {
        "summary": "AI 正在改变前端开发方式",
        "callToAction": "立即尝试这些工具",
        "wordCount": 200
      },
      "keywords": ["AI", "前端开发", "GitHub Copilot", "效率提升"],
      "seoTitle": "AI 赋能前端开发:效率提升完全指南",
      "metaDescription": "深入了解 AI 工具如何提升前端开发效率..."
    },
    "duration": 2580,           // 执行时间(毫秒)
    "tokensUsed": 1234          // 使用的 token 数
  }
}

错误响应

json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "topic 字段不能为空"
  }
}

状态码

  • 200 OK: 成功
  • 400 Bad Request: 参数错误
  • 401 Unauthorized: 未认证
  • 429 Too Many Requests: 请求过于频繁
  • 500 Internal Server Error: 服务器错误

2. 写作 Agent - 生成章节内容(流式)

POST/api/ai/write

根据大纲生成具体的章节内容,支持流式响应

请求参数

typescript
interface WriteRequest {
  topic: string;              // 文章主题
  type: string;               // 文章类型
  tone: string;               // 语气风格
  audience: string;           // 目标受众
  heading: string;            // 章节标题
  points: string[];           // 核心要点
  wordCount: number;          // 目标字数
  tips?: string;              // 写作建议(可选)
  previousContent?: string;   // 前文内容(可选,保持连贯性)
}

请求示例

typescript
const response = await fetch('/api/ai/write', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
  },
  body: JSON.stringify({
    topic: 'AI 在前端开发中的应用',
    type: 'blog',
    tone: 'professional',
    audience: '前端开发者',
    heading: 'AI 代码生成工具',
    points: [
      'GitHub Copilot 的使用技巧',
      '如何提高代码建议的准确性'
    ],
    wordCount: 500,
    tips: '提供具体的代码示例',
  }),
});

// 流式读取响应
const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const chunk = decoder.decode(value);
  console.log(chunk); // 实时输出内容
}

响应格式

plain
流式文本输出(Plain Text)

示例:
## AI 代码生成工具

在现代前端开发中,AI 代码生成工具已经成为...

GitHub Copilot 是目前最受欢迎的 AI 编程助手...

(内容持续流式输出)

也支持非流式响应(添加 stream: false 参数):

json
{
  "success": true,
  "data": {
    "content": "## AI 代码生成工具\n\n完整内容...",
    "wordCount": 523,
    "duration": 5240,
    "tokensUsed": 2456
  }
}

3. 优化 Agent - 内容质量分析

POST/api/ai/optimize

分析内容质量并提供优化建议

请求参数

typescript
interface OptimizeRequest {
  content: string;            // 要优化的内容
  type: string;               // 优化类型(可选,默认 comprehensive)
                             // grammar, seo, readability, tone, comprehensive
}

请求示例

typescript
const response = await fetch('/api/ai/optimize', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
  },
  body: JSON.stringify({
    content: '文章内容...',
    type: 'comprehensive',
  }),
});

const data = await response.json();

响应示例

json
{
  "success": true,
  "data": {
    "analysis": {
      "overallScore": 85,
      "readability": {
        "score": 82,
        "level": "中等",
        "issues": [
          "第 3 段句子过长,建议拆分",
          "专业术语较多,建议添加解释"
        ],
        "suggestions": [
          "使用更多的小标题划分内容",
          "适当使用列表和图表"
        ]
      },
      "grammar": {
        "score": 95,
        "errors": [
          {
            "original": "它的功能",
            "correction": "它的功能是",
            "position": 245,
            "explanation": "句子不完整"
          }
        ]
      },
      "seo": {
        "score": 88,
        "keywordDensity": {
          "AI": 2.5,
          "前端开发": 1.8,
          "效率": 1.2
        },
        "suggestions": [
          "标题中添加核心关键词",
          "适当增加关键词 '前端开发' 的出现频率"
        ]
      },
      "tone": {
        "score": 90,
        "detected": "professional",
        "consistency": "很好",
        "issues": []
      }
    },
    "improvements": [
      {
        "type": "grammar",
        "original": "它的功能",
        "improved": "它的功能是帮助开发者...",
        "reason": "句子完整性"
      },
      {
        "type": "readability",
        "original": "很长的句子...",
        "improved": "拆分后的句子。另一个句子。",
        "reason": "提高可读性"
      }
    ],
    "duration": 3200,
    "tokensUsed": 1890
  }
}

项目管理接口

4. 创建项目

POST/api/projects

创建新的内容项目

请求参数

typescript
interface CreateProjectRequest {
  title: string;                    // 项目标题(必填)
  description?: string;             // 项目描述(可选)
  type: string;                     // 文章类型
  targetAudience?: string;          // 目标受众
  wordCountTarget?: number;         // 目标字数
  tone?: string;                    // 语气风格
}

请求示例

typescript
const response = await fetch('/api/projects', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
  },
  body: JSON.stringify({
    title: 'AI 在前端开发中的应用',
    description: '探讨 AI 工具如何提升前端开发效率',
    type: 'blog',
    targetAudience: '前端开发者',
    wordCountTarget: 2000,
    tone: 'professional',
  }),
});

响应示例

json
{
  "success": true,
  "data": {
    "id": "uuid-here",
    "title": "AI 在前端开发中的应用",
    "type": "blog",
    "status": "draft",
    "createdAt": "2024-01-28T10:00:00Z"
  }
}

5. 获取项目列表

GET/api/projects

获取当前用户的所有项目

查询参数

plain
?status=completed     // 过滤状态(可选)
&type=blog           // 过滤类型(可选)
&page=1              // 页码(默认 1)
&limit=10            // 每页数量(默认 10)
&sort=created_at     // 排序字段(默认 created_at)
&order=desc          // 排序方向(asc/desc,默认 desc)

请求示例

typescript
const response = await fetch(
  '/api/projects?status=completed&limit=20',
  {
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  }
);

响应示例

json
{
  "success": true,
  "data": {
    "projects": [
      {
        "id": "uuid-1",
        "title": "AI 在前端开发中的应用",
        "type": "blog",
        "status": "completed",
        "wordCount": 2134,
        "completionPercentage": 106.7,
        "createdAt": "2024-01-28T10:00:00Z",
        "updatedAt": "2024-01-28T15:30:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 15,
      "pages": 1
    }
  }
}

6. 获取项目详情

GET/api/projects/:id

获取项目的完整信息,包括大纲和章节

请求示例

typescript
const response = await fetch('/api/projects/uuid-here', {
  headers: {
    'Authorization': `Bearer ${token}`,
  },
});

响应示例

json
{
  "success": true,
  "data": {
    "project": {
      "id": "uuid-here",
      "title": "AI 在前端开发中的应用",
      "type": "blog",
      "status": "completed",
      "outline": {
        "title": "AI 赋能前端",
        "sections": [...]
      },
      "sections": [
        {
          "id": "section-uuid-1",
          "heading": "引言",
          "content": "# 引言\n\n内容...",
          "wordCount": 234,
          "status": "completed",
          "orderIndex": 0
        }
      ],
      "statistics": {
        "totalWords": 2134,
        "completedSections": 5,
        "totalSections": 5,
        "completionPercentage": 100
      }
    }
  }
}

7. 更新项目

PATCH/api/projects/:id

更新项目信息

请求参数

typescript
interface UpdateProjectRequest {
  title?: string;
  description?: string;
  status?: string;
  // 其他可更新的字段...
}

请求示例

typescript
const response = await fetch('/api/projects/uuid-here', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
  },
  body: JSON.stringify({
    status: 'completed',
  }),
});

8. 删除项目

DELETE/api/projects/:id

删除项目(级联删除所有相关数据)

请求示例

typescript
const response = await fetch('/api/projects/uuid-here', {
  method: 'DELETE',
  headers: {
    'Authorization': `Bearer ${token}`,
  },
});

响应示例

json
{
  "success": true,
  "message": "项目已删除"
}

统计分析接口

9. 获取使用统计

GET/api/stats/usage

获取 AI 使用统计(token 数、成本等)

查询参数

plain
?startDate=2024-01-01    // 开始日期(可选)
&endDate=2024-01-31      // 结束日期(可选)
&groupBy=day             // 分组方式(day/week/month,默认 day)

响应示例

json
{
  "success": true,
  "data": {
    "summary": {
      "totalRequests": 156,
      "totalTokens": 234500,
      "totalCost": 9.38,
      "averageTokensPerRequest": 1503
    },
    "byDate": [
      {
        "date": "2024-01-28",
        "requests": 12,
        "tokens": 18450,
        "cost": 0.74
      }
    ],
    "byAgent": {
      "planner": {
        "requests": 45,
        "tokens": 67500,
        "cost": 2.70
      },
      "writer": {
        "requests": 89,
        "tokens": 145000,
        "cost": 5.80
      },
      "optimizer": {
        "requests": 22,
        "tokens": 22000,
        "cost": 0.88
      }
    }
  }
}

🔧 错误处理

错误码说明

错误码 说明 示例
VALIDATION_ERROR 参数验证失败 缺少必填字段
AUTHENTICATION_ERROR 认证失败 Token 无效或过期
AUTHORIZATION_ERROR 权限不足 访问他人的项目
NOT_FOUND 资源不存在 项目 ID 不存在
RATE_LIMIT_EXCEEDED 超过速率限制 请求过于频繁
AI_SERVICE_ERROR AI 服务错误 DeepSeek API 调用失败
DATABASE_ERROR 数据库错误 数据库连接失败
INTERNAL_ERROR 服务器内部错误 未预期的错误

错误响应格式

json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "topic 字段不能为空",
    "details": {
      "field": "topic",
      "reason": "required"
    }
  }
}

速率限制

限制规则

接口类型 限制 说明
AI 接口 10 次/分钟 防止滥用
项目管理 60 次/分钟 正常使用
统计查询 30 次/分钟 中等限制

响应 Header

http
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 7
X-RateLimit-Reset: 1706432400

超限响应

json
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "请求过于频繁,请稍后再试",
    "retryAfter": 45
  }
}

最佳实践

1. 错误处理

typescript
async function callAPI(url: string, options: RequestInit) {
  try {
    const response = await fetch(url, options);
    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error.message);
    }

    return data;
  } catch (error) {
    console.error('API 调用失败:', error);
    throw error;
  }
}

2. 重试机制

typescript
async function callAPIWithRetry(
  url: string,
  options: RequestInit,
  maxRetries = 3
) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await callAPI(url, options);
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
}

3. 流式响应处理

typescript
async function handleStreamResponse(response: Response) {
  const reader = response.body!.getReader();
  const decoder = new TextDecoder();
  let content = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    content += chunk;

    // 实时更新 UI
    updateUI(content);
  }

  return content;
}

面试要点

API 设计亮点

1. RESTful 设计

plain
"我遵循 RESTful API 设计原则:
- 使用标准 HTTP 方法(GET/POST/PATCH/DELETE)
- 资源命名清晰(/projects, /api/ai/plan)
- 状态码使用规范(200/400/401/500)
- 统一的响应格式"
2. 流式响应
plain
"写作 Agent 支持流式响应,使用 ReadableStream API。
这样用户可以实时看到内容生成,体验更好。
我还提供了非流式版本,满足不同需求。"
3. 错误处理
plain
"我设计了统一的错误处理机制:
- 定义了清晰的错误码
- 提供详细的错误信息
- 包含调试用的 details 字段
- HTTP 状态码和业务错误码分离"
4. 速率限制
plain
"为了防止滥用和保护服务,我实现了速率限制。
使用 Redis 记录请求次数,超限返回 429 状态码。
在响应 Header 中返回限制信息,方便客户端处理。"