1. 什么是 OpenAPI 规范
OpenAPI 规范(OpenAPI Specification,简称 OAS)是一种用于描述 HTTP API 的机器可读格式。它基于 JSON 或 YAML 编写,能够完整定义接口的路径、请求参数、请求体、响应结构、认证方式等信息。借助 OpenAPI 规范,开发者可以生成客户端 SDK、服务端脚手架、接口文档和自动化测试工具。
OpenAPI 规范的前身是 Swagger 规范,2015 年由 SmartBear 捐赠给 Linux 基金会,并更名为 OpenAPI Initiative。目前最新的稳定版本是 OpenAPI 3.0.x 和 3.1.x,本文以 3.0.3 版本为例进行讲解。
2. OpenAPI 文档的基本结构
一份完整的 OpenAPI 文档通常包含以下几个顶层字段:
- openapi:声明使用的 OpenAPI 版本号。
- info:描述 API 的基本信息,如标题、版本、描述。
- servers:定义 API 的服务地址列表。
- paths:定义所有可用的接口路径和操作。
- components:存放可复用的数据模型、参数、响应等组件。
下面是一个最简单的 OpenAPI 文档示例:
openapi: 3.0.3 info: title: 用户服务 API version: 1.0.0 description: 提供用户注册、查询和删除功能 servers: - url: https://api.example.com/v1 paths: /users: get: summary: 获取用户列表 responses: '200': description: 成功返回用户列表3. 定义接口路径与操作
paths 字段是 OpenAPI 文档的核心,它按 URL 路径组织接口。每个路径下可以定义多个 HTTP 方法,如 get、post、put、delete 等。每个操作对象可以包含 summary、description、parameters、requestBody、responses 等字段。
下面是一个包含 GET 和 POST 操作的示例:
paths: /users: get: summary: 获取用户列表 parameters: - name: page in: query required: false schema: type: integer default: 1 responses: '200': description: 成功返回用户列表 content: application/json: schema: type: array items: $ref: '#/components/schemas/User' post: summary: 创建新用户 requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/User' responses: '201': description: 用户创建成功 content: application/json: schema: $ref: '#/components/schemas/User'4. 定义数据模型
components.schemas 用于定义可复用的数据模型。通过 $ref 引用,可以避免在多个接口中重复定义相同的数据结构。下面是一个用户模型的示例:
components: schemas: User: type: object required: - id - name - email properties: id: type: integer format: int64 description: 用户唯一标识 name: type: string description: 用户姓名 email: type: string format: email description: 用户邮箱 createdAt: type: string format: date-time description: 创建时间在接口定义中,可以通过 $ref 引用该模型:
paths: /users/{userId}: get: summary: 根据 ID 获取用户 parameters: - name: userId in: path required: true schema: type: integer format: int64 responses: '200': description: 成功返回用户信息 content: application/json: schema: $ref: '#/components/schemas/User' '404': description: 用户不存在5. 定义请求参数
OpenAPI 支持四种参数位置:path、query、header、cookie。每个参数需要声明名称、位置、是否必填以及数据类型。下面是一个包含多种参数类型的示例:
paths: /search: get: summary: 搜索商品 parameters: - name: keyword in: query required: true schema: type: string description: 搜索关键词 - name: category in: query required: false schema: type: string description: 商品分类 - name: X-Request-Id in: header required: false schema: type: string description: 请求追踪 ID responses: '200': description: 搜索成功6. 定义请求体与响应
requestBody 用于描述 POST、PUT 等操作需要携带的请求体内容。responses 用于描述接口可能返回的各种状态码和响应结构。下面是一个完整的创建订单示例:
paths: /orders: post: summary: 创建订单 requestBody: required: true content: application/json: schema: type: object required: - productId - quantity properties: productId: type: integer format: int64 quantity: type: integer minimum: 1 remark: type: string responses: '201': description: 订单创建成功 content: application/json: schema: type: object properties: orderId: type: integer format: int64 status: type: string enum: - CREATED - PAID - SHIPPED '400': description: 请求参数错误 content: application/json: schema: type: object properties: code: type: integer message: type: string7. 定义认证方式
OpenAPI 支持多种认证方式,包括 API Key、HTTP Basic、Bearer Token 和 OAuth2。通过 components.securitySchemes 定义认证方案,再通过 security 字段应用到全局或单个操作。下面是一个 Bearer Token 认证的示例:
components: securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT security: - bearerAuth: [] paths: /me: get: summary: 获取当前登录用户信息 security: - bearerAuth: [] responses: '200': description: 成功返回当前用户信息 content: application/json: schema: $ref: '#/components/schemas/User' '401': description: 未认证或 Token 无效8. 使用 OpenAPI 生成代码与文档
编写好 OpenAPI 文档后,可以借助工具链自动生成客户端 SDK、服务端脚手架和交互式文档。常用的工具包括:
- Swagger UI:将 OpenAPI 文档渲染为可交互的 API 文档页面。
- OpenAPI Generator:根据文档生成多种语言的客户端和服务端代码。
- ReDoc:生成简洁美观的 API 参考文档。
下面是一个使用 OpenAPI Generator 生成 Java 客户端的命令行示例:
openapi-generator-cli generate \ -i openapi.yaml \ -g java \ -o ./generated-client \ --library okhttp \ --group-id com.example \ --artifact-id user-client生成完成后,可以在项目中直接引用生成的客户端代码,例如:
UserApi api = new UserApi(); User user = api.getUserById(1001L); System.out.println(user.getName());9. 常见问题与最佳实践
在实际使用 OpenAPI 规范时,有几个常见问题值得注意:
- 版本管理:建议在 info.version 中维护 API 版本,并在 URL 路径中体现,如 /v1/users。
- 模型复用:尽量将公共数据结构抽取到 components.schemas 中,避免重复定义。
- 错误响应:为每个接口定义完整的错误响应结构,方便客户端统一处理异常。
- 文档同步:将 OpenAPI 文档纳入版本控制,并在 CI/CD 流程中校验文档与代码的一致性。
下面是一个包含错误码约定的响应模型示例:
components: schemas: ApiError: type: object required: - code - message properties: code: type: integer description: 业务错误码 message: type: string description: 错误描述 details: type: object description: 附加错误详情10. 总结
OpenAPI 规范为 API 设计、开发、测试和文档化提供了一套统一的标准。通过 YAML 或 JSON 描述接口的路径、参数、请求体、响应和认证方式,团队可以在不同语言和工具之间共享同一份接口契约。掌握 OpenAPI 规范,不仅能够提升接口文档的质量,还能显著提高前后端协作和自动化测试的效率。