5.0 KiB
5.0 KiB
API 文档说明
📚 Swagger 文档已集成
Steel Prices Service 现已集成完整的 Swagger API 文档系统!
访问方式
启动服务后,可以通过以下方式访问 API 文档:
1. Swagger UI 界面(推荐)
http://localhost:3000/api-docs
特点:
- 📖 交互式 API 文档
- 🧪 可直接在浏览器中测试 API
- 📝 完整的请求/响应示例
- 🔍 参数说明和验证规则
- 🎨 美观的用户界面
2. JSON 格式的 OpenAPI 规范
http://localhost:3000/api-docs.json
用于:
- 导入到其他 API 工具(Postman、Insomnia)
- 自动生成客户端 SDK
- API 版本管理
3. API 信息接口
http://localhost:3000/
返回所有可用的 API 端点和文档链接。
📖 文档内容
API 端点分类
Health(健康检查)
GET /api/health- 检查服务状态
Prices(价格查询)
GET /api/prices/region- 按地区查询价格GET /api/prices/search- 多条件搜索价格GET /api/prices/stats- 价格统计分析GET /api/prices/trend- 价格趋势分析
Data(数据管理)
POST /api/prices/import- 批量导入价格数据
数据模型
Price(价格数据)
- region - 地区(必填)
- city - 城市
- material - 材质(必填)
- specification - 规格型号
- price - 价格(必填)
- unit - 单位
- date - 日期(必填)
- source - 数据来源
- warehouse - 仓库/厂家
PriceStats(价格统计)
- count - 记录数量
- avgPrice - 平均价格
- minPrice - 最低价格
- maxPrice - 最高价格
- stdDev - 标准差
- trend - 价格趋势
- changeRate - 变化率
🧪 如何使用 Swagger UI
1. 浏览 API
- 打开
http://localhost:3000/api-docs - 展开左侧的 API 分类标签
- 点击感兴趣的 API 端点
2. 测试 API
- 在 API 详情页点击 "Try it out" 按钮
- 填写必填参数(标红的字段)
- 点击 "Execute" 执行请求
- 查看响应结果
3. 查看数据模型
- 滚动到页面底部的 "Schemas" 部分
- 点击模型名称查看详细字段说明
- 查看示例数据格式
📝 示例:测试 API
示例 1:按地区查询价格
请求:
GET /api/prices/region?region=昆明&date=2026-01-05
在 Swagger UI 中的步骤:
- 展开
GET /api/prices/region - 点击 "Try it out"
- 在 region 字段输入:
昆明 - 在 date 字段输入:
2026-01-05(可选) - 点击 "Execute"
- 查看响应结果
示例 2:搜索价格数据
请求:
GET /api/prices/search?material=HPB300&page=1&pageSize=20
在 Swagger UI 中的步骤:
- 展开
GET /api/prices/search - 点击 "Try it out"
- 在 material 字段输入:
HPB300 - 在 page 字段输入:
1 - 在 pageSize 字段输入:
20 - 点击 "Execute"
- 查看响应结果和分页信息
示例 3:获取价格统计
请求:
GET /api/prices/stats?region=昆明&material=HPB300&days=30
在 Swagger UI 中的步骤:
- 展开
GET /api/prices/stats - 点击 "Try it out"
- 在 region 字段输入:
昆明 - 在 material 字段输入:
HPB300 - 在 days 字段输入:
30 - 点击 "Execute"
- 查看统计数据
🔧 Swagger UI 配置
启用的功能
- ✅ Explorer - API 列表导航
- ✅ Try It Out - 直接测试 API
- ✅ Request Duration - 显示请求耗时
- ✅ Filter - 搜索和过滤 API
- ✅ Request Headers - 显示请求头
- ✅ Doc Expansion - 列表展开方式
自定义配置
位置:src/app.js
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
explorer: true, // 启用 API 导航
customCss: '.swagger-ui .topbar { display: none }', // 自定义 CSS
customSiteTitle: 'Steel Prices Service API Documentation', // 页面标题
swaggerOptions: {
persistAuthorization: true, // 持久化认证
displayRequestDuration: true, // 显示请求耗时
docExpansion: 'list', // 列表展开模式
filter: true, // 启用过滤
showRequestHeaders: true, // 显示请求头
tryItOutEnabled: true // 启用测试功能
}
}));
📚 相关文档
- src/config/swagger.js - Swagger 配置文件
- src/routes/api.js - API 路由和注解
- OpenAPI 3.0 规范 - 官方规范
🎯 快速开始
-
启动服务
npm start -
打开浏览器
http://localhost:3000/api-docs -
开始测试 API
- 选择一个 API 端点
- 点击 "Try it out"
- 填写参数并执行
💡 提示
- 所有参数都有详细的说明和示例
- 必填参数会用红色标记
- 响应数据包含完整的 JSON Schema
- 可以直接复制示例代码使用