# OpenAPI文档使用指南 ## 概述 OpenAPI(原名Swagger)是一个用于描述、生成、消费和可视化RESTful Web服务的规范。本项目已集成OpenAPI文档,提供交互式API文档界面。 ## 访问文档 ### 开发环境 启动开发服务器后,访问: ``` http://localhost:3000/api-docs ``` ### 生产环境 部署后访问: ``` https://your-domain.com/api-docs ``` ## 文档结构 ### API端点 | 端点 | 方法 | 描述 | 认证 | |------|------|------|------| | `/api/health` | GET | 健康检查 | 无 | | `/api/admin/content` | GET | 获取内容列表 | 需要管理员权限 | | `/api/admin/content` | POST | 创建新内容 | 需要管理员权限 | ### 数据模型 #### Content(内容) ```typescript interface Content { id: number; type: 'news' | 'case' | 'product' | 'service'; title: string; content: string; status: 'draft' | 'published' | 'archived'; createdAt: Date; updatedAt: Date; } ``` #### User(用户) ```typescript interface User { id: number; name: string; email: string; role: 'admin' | 'editor' | 'viewer'; } ``` #### Config(配置) ```typescript interface Config { key: string; value: string; description: string; } ``` ## 使用Swagger UI ### 浏览API 1. 访问 `/api-docs` 2. 点击任意API端点展开详情 3. 查看请求参数、响应格式和示例 ### 测试API #### 无需认证的API 1. 点击"Try it out"按钮 2. 填写必要参数 3. 点击"Execute"执行请求 4. 查看响应结果 示例:健康检查API ```bash curl -X GET "http://localhost:3000/api/health" -H "accept: application/json" ``` #### 需要认证的API 1. 先登录获取访问令牌 2. 点击页面右上角的"Authorize"按钮 3. 输入Bearer令牌:`Bearer your-access-token` 4. 点击"Authorize"确认 5. 现在可以测试需要认证的API 示例:获取内容列表 ```bash curl -X GET "http://localhost:3000/api/admin/content?page=1&limit=20" \ -H "accept: application/json" \ -H "Authorization: Bearer your-access-token" ``` ## 为API添加文档 ### 步骤1:添加JSDoc注释 在API路由文件中添加JSDoc注释: ```typescript /** * @openapi * /api/your-endpoint: * get: * tags: * - YourTag * summary: 简短描述 * description: 详细描述 * operationId: getYourData * parameters: * - name: id * in: path * required: true * schema: * type: integer * responses: * 200: * description: 成功响应 * content: * application/json: * schema: * type: object * properties: * success: * type: boolean * data: * type: object */ export async function GET(request: NextRequest) { // API实现 } ``` ### 步骤2:定义请求体 对于POST/PUT请求: ```typescript /** * @openapi * /api/your-endpoint: * post: * requestBody: * required: true * content: * application/json: * schema: * type: object * required: * - name * - email * properties: * name: * type: string * email: * type: string * format: email */ ``` ### 步骤3:引用共享Schema 使用`$ref`引用共享数据模型: ```typescript /** * @openapi * /api/admin/content: * get: * responses: * 200: * content: * application/json: * schema: * $ref: '#/components/schemas/Content' */ ``` ## OpenAPI规范文件 ### 获取规范文件 访问以下端点获取原始OpenAPI规范: ``` GET /api/docs ``` ### 使用规范文件 1. **导入到Postman** - 打开Postman - 点击"Import" - 选择"Link" - 输入:`http://localhost:3000/api/docs` - 点击"Import" 2. **生成客户端代码** - 使用OpenAPI Generator - 支持多种语言:TypeScript, Python, Java等 3. **API测试** - 导入到测试工具 - 自动生成测试用例 ## 最佳实践 ### ✅ 推荐做法 1. **完整的描述** - 提供清晰的summary和description - 说明参数的作用和限制 - 提供示例值 2. **准确的类型定义** - 使用正确的数据类型 - 标注必填字段 - 定义枚举值 3. **完整的响应定义** - 定义所有可能的响应状态码 - 提供错误响应格式 - 包含示例数据 4. **合理的标签分组** - 按功能模块分组 - 使用一致的命名 - 避免过多标签 ### ❌ 避免的做法 1. **不要省略错误响应** ```typescript // ❌ 不好 responses: * 200: * description: 成功 // ✅ 好 responses: * 200: * description: 成功 * 400: * description: 参数错误 * 401: * description: 未授权 * 500: * description: 服务器错误 ``` 2. **不要使用模糊的描述** ```typescript // ❌ 不好 summary: 获取数据 // ✅ 好 summary: 获取内容列表 description: 管理员获取内容列表,支持分页、筛选和搜索 ``` 3. **不要忽略认证要求** ```typescript // ✅ 始终标注认证要求 security: * - bearerAuth: [] ``` ## 高级功能 ### 添加示例 ```typescript /** * @openapi * /api/admin/content: * post: * requestBody: * content: * application/json: * examples: * newsExample: * summary: 新闻示例 * value: * type: news * title: 新闻标题 * content: 新闻内容 */ ``` ### 添加标签描述 在`/api/docs/route.ts`中: ```typescript tags: [ { name: 'Content', description: '内容管理相关接口', }, { name: 'Admin', description: '管理员相关接口', }, ], ``` ### 添加服务器配置 ```typescript servers: [ { url: 'http://localhost:3000', description: '开发服务器', }, { url: 'https://api.novalon.cn', description: '生产服务器', }, ], ``` ## CI/CD集成 ### 验证OpenAPI规范 ```bash # 安装验证工具 npm install -g @redocly/cli # 验证规范 redocly lint http://localhost:3000/api/docs ``` ### 生成文档 ```bash # 安装Redoc npm install -g redoc # 生成静态HTML文档 redocly build-docs http://localhost:3000/api/docs -o api-docs.html ``` ### GitHub Actions示例 ```yaml name: API Documentation on: push: branches: [main] jobs: validate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '18' - name: Install dependencies run: npm ci - name: Start server run: npm run dev & env: CI: true - name: Wait for server run: npx wait-on http://localhost:3000/api/docs - name: Validate OpenAPI spec run: npx @redocly/cli lint http://localhost:3000/api/docs ``` ## 故障排查 ### 问题1:文档页面无法加载 **症状**:访问`/api-docs`显示加载中或空白页 **解决方案**: ```bash # 检查API端点是否正常 curl http://localhost:3000/api/docs # 检查浏览器控制台错误 # 打开开发者工具查看Network和Console标签 ``` ### 问题2:API不显示在文档中 **症状**:某些API端点未出现在文档中 **解决方案**: ```typescript // 检查JSDoc注释格式 // 确保使用 @openapi 标签 /** * @openapi // ← 必须是这个标签 * /api/your-endpoint: * get: */ // 检查apis路径配置 apis: [ './src/app/api/**/route.ts', // ← 确保路径正确 ], ``` ### 问题3:认证失败 **症状**:使用Authorize按钮后仍然无法访问需要认证的API **解决方案**: ```bash # 确保令牌格式正确 Bearer your-access-token # ← 注意Bearer前缀 # 检查令牌是否有效 curl -H "Authorization: Bearer your-token" http://localhost:3000/api/admin/content ``` ## 参考资源 - [OpenAPI规范](https://swagger.io/specification/) - [Swagger UI文档](https://swagger.io/tools/swagger-ui/) - [swagger-jsdoc文档](https://github.com/surnet/swagger-jsdoc) - [OpenAPI Generator](https://openapi-generator.tech/) - [Redoc文档](https://redocly.com/docs/redoc/) ## 总结 OpenAPI文档已完全集成到项目中,提供了: ✅ **交互式API文档** ✅ **自动生成规范** ✅ **在线测试功能** ✅ **认证支持** ✅ **多格式导出** 通过合理使用OpenAPI文档,可以: - 提升API可用性 - 减少沟通成本 - 自动化API测试 - 生成客户端SDK