Ubuntu上Swagger API设计实操指南
一 环境准备与工具链
- 安装 Node.js 18.x 与 npm(Ubuntu 20.04/22.04 推荐 LTS):
- curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
- sudo apt-get install -y nodejs
- 全局安装 OpenAPI 常用工具:
- npm install -g @openapitools/openapi-generator-cli
- npm install -g swagger-cli
- npm install -g redoc-cli
- 验证安装:openapi-generator-cli version、swagger-cli --version、redoc-cli version
- 建议项目结构(便于模块化与维护):
- project-root/
- openapi/
- spec.yaml
- components/
- schemas/
- parameters/
- responses/
- security/
- paths/
- examples/
- generated/
- docs/
- tests/
二 设计流程与规范要点
- 采用 OpenAPI 3.x(业界常称“Swagger 3”)编写规范,优先使用 YAML 提升可读性。
- 规范骨架与关键字段:
- openapi: 3.0.0
- info: { title, description, version, contact, license }
- servers: 区分 生产/沙箱 环境 URL
- paths: 资源路径与 GET/POST/PUT/PATCH/DELETE 操作
- components: 可复用的 schemas/parameters/responses/securitySchemes
- security: 全局安全应用
- 路径与操作设计要点:
- 使用 /v1 等路径版本;资源命名复数、层级清晰(如 /products/{id}/reviews)
- 为操作设置 operationId(便于代码生成与追踪)
- 请求参数与响应体使用 $ref 复用组件,减少冗余
- 组件与数据模型:
- 明确定义 required 字段、类型、格式(如 date-time、int64、email)
- 统一 分页 与 错误响应 模型,便于客户端处理
- 安全方案:
- 支持 Bearer JWT、API Key、HTTP Basic、OAuth2(在 components.securitySchemes 定义,并在 security 应用)
- 本地编辑与校验:
- 使用 Swagger Editor 本地编辑与实时预览
- 使用 swagger-cli validate 校验规范合法性
示例片段(openapi/spec.yaml)
openapi: 3.0.0
info:
title: 示例 API
description: 商品与订单示例
version: 1.0.0
servers:
- url: https://api.example.com/v1
description: 生产环境
- url: https://sandbox.api.example.com/v1
description: 沙箱环境
paths:
/products:
get:
summary: 获取商品列表
operationId: getProducts
tags: [Products]
parameters:
- $ref: ‘#/components/parameters/PageParam’
- $ref: ‘#/components/parameters/LimitParam’
responses:
‘200’:
description: 成功
content:
application/json:
schema:
$ref: ‘#/components/schemas/ProductList’
components:
schemas:
Product:
type: object
required: [id, name, price]
properties:
id: { type: integer, format: int64 }
name: { type: string, maxLength: 100 }
price: { type: number, format: float, minimum: 0 }
createdAt: { type: string, format: date-time }
ProductList:
type: object
properties:
data: { type: array, items: { $ref: ‘#/components/schemas/Product’ } }
pagination: { $ref: ‘#/components/schemas/Pagination’ }
parameters:
PageParam:
name: page
in: query
required: false
schema: { type: integer, minimum: 1, default: 1 }
LimitParam:
name: limit
in: query
required: false
schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
responses:
BadRequest:
description: 请求参数错误
content:
application/json:
schema: { $ref: ‘#/components/schemas/Error’ }
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
security:
- BearerAuth: []
三 在 Ubuntu 中集成与发布文档
- Node.js + Express 集成 Swagger UI Express:
- 安装:npm install swagger-ui-express yamljs
- 代码示例:
- const express = require(‘express’); const swaggerUi = require(‘swagger-ui-express’); const YAML = require(‘yamljs’);
- const app = express(); const swaggerDocument = YAML.load(‘./openapi/spec.yaml’);
- app.use(‘/api-docs’, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
- app.listen(3000, () => console.log(‘Server on :3000, docs -> /api-docs’));
- 静态托管 Swagger UI(Nginx 示例):
- 将 swagger-ui-dist 内容复制到 /var/www/html/swagger-ui
- Nginx 配置 root /var/www/html/swagger-ui; 访问 http:///swagger-ui/index.html
- 生成与预览文档:
- 生成静态站点:redoc-cli bundle openapi/spec.yaml -o docs/index.html
- 访问 http:///docs/index.html 查看 ReDoc 文档
四 代码生成、Mock 与自动化测试
- 代码生成(服务端/客户端/文档):
- openapi-generator-cli generate -i openapi/spec.yaml -g spring -o ./generated/spring-server
- openapi-generator-cli generate -i openapi/spec.yaml -g typescript-axios -o ./generated/ts-client
- Mock 服务(开发联调前):
- 使用 swagger-mock-api 基于规范快速启动模拟服务,便于前后端并行
- 自动化测试:
- 使用 requests/pytest 等编写接口测试,结合 CI 对核心路径做回归
- 持续集成建议:
- 在 CI 中加入规范校验(swagger-cli validate)、生成代码与文档、运行测试并上传产物
五 最佳实践与常见坑
- 设计与治理:
- 模块化组织规范(components 复用)、版本化路径(/v1)、强类型与约束(必填、长度、范围)
- 统一 错误模型 与 分页模型,减少前后端沟通成本
- 安全与合规:
- 在 components.securitySchemes 明确定义 JWT/API Key/OAuth2,并在需要处应用
- 注意:Swagger UI 不提供鉴权,生产环境应限制访问或置于内网
- 工具选择与兼容:
- 新项目优先 OpenAPI 3.x + springdoc(Spring Boot 3+ 推荐),旧项目迁移自 Springfox
- 保持规范与实现一致:用生成代码与自动化测试做“活文档”