|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
引言
在当今的软件开发世界中,API(应用程序编程接口)扮演着连接不同软件系统的关键角色。无论是构建微服务架构、移动应用后端,还是第三方集成,良好的API文档都是确保开发者能够轻松理解和使用你的服务的关键。Swagger(现在称为OpenAPI规范)已经成为行业标准,为RESTful API提供了一套强大而灵活的文档框架。
本教程将深入探讨Swagger JSON配置,帮助你从零开始创建专业、全面且易于维护的API文档。无论你是API设计的新手还是有经验的开发者,本指南都将提供实用的步骤和最佳实践,让你的API文档达到专业水平。
Swagger基础
什么是Swagger?
Swagger是一套围绕OpenAPI规范构建的开源工具,用于设计、构建、记录和使用RESTful Web服务。它允许你描述API的结构,以便机器可以读取它们的能力。通过Swagger,你可以:
• 生成交互式API文档
• 自动生成客户端SDK代码
• 进行API测试
• 确保API设计与实现保持一致
OpenAPI规范
OpenAPI规范(OAS)是Swagger的基础,它定义了一个标准的、与语言无关的接口到RESTful API。最新的版本是OpenAPI 3.0,它引入了许多改进和新特性,如:
• 更好的可重用性
• 增强的安全支持
• 改进的内容协商
• 更灵活的回调支持
• 更强的链接支持
环境准备
在开始配置Swagger JSON之前,你需要准备一些工具和环境:
1. 文本编辑器
选择一个支持JSON语法高亮和验证的文本编辑器,如:
• Visual Studio Code
• WebStorm
• Sublime Text
• Atom
2. Swagger编辑器
Swagger提供了在线编辑器,可以帮助你实时预览和验证你的Swagger JSON配置:
Swagger Editor
3. 本地开发环境(可选)
如果你想在本地运行Swagger UI,可以设置一个简单的HTTP服务器:
- # 使用Node.js的http-server
- npm install -g http-server
- http-server -o
- # 或者使用Python的SimpleHTTPServer
- python -m http.server 8000
复制代码
创建基本的Swagger JSON配置
让我们从创建一个基本的Swagger JSON配置文件开始。这个文件通常命名为swagger.json或openapi.json。
最小配置示例
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0"
- },
- "paths": {}
- }
复制代码
这个最小配置包含了三个必需的部分:
1. openapi- 指定使用的OpenAPI规范版本
2. info- 提供API的元数据
3. paths- 定义API的路径和操作
完整的基本配置
让我们扩展这个基本配置,添加更多有用的信息:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "description": "这是一个示例API,用于演示Swagger JSON配置",
- "version": "1.0.0",
- "contact": {
- "name": "API支持",
- "email": "support@example.com",
- "url": "https://example.com/support"
- },
- "license": {
- "name": "MIT",
- "url": "https://opensource.org/licenses/MIT"
- }
- },
- "servers": [
- {
- "url": "https://api.example.com/v1",
- "description": "生产服务器"
- },
- {
- "url": "https://dev-api.example.com/v1",
- "description": "开发服务器"
- }
- ],
- "paths": {}
- }
复制代码
在这个扩展版本中,我们添加了:
• description- API的详细描述
• contact- 联系信息
• license- 许可证信息
• servers- API服务器列表
深入Swagger JSON结构
现在,让我们深入了解Swagger JSON的各个部分,以及如何配置它们来创建专业的API文档。
Info对象
info对象提供关于API的元数据,它是Swagger JSON的必需部分。以下是一个完整的info对象示例:
- "info": {
- "title": "用户管理API",
- "description": "这是一个完整的用户管理系统API,提供用户注册、登录、资料管理等功能。\n\n## 功能特点\n- 用户注册和认证\n- 用户资料管理\n- 角色和权限管理\n- 密码重置\n\n## 使用指南\n要使用此API,开发者需要先注册获取API密钥。",
- "termsOfService": "https://example.com/terms",
- "contact": {
- "name": "API支持团队",
- "email": "api-support@example.com",
- "url": "https://example.com/contact"
- },
- "license": {
- "name": "Apache 2.0",
- "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
- },
- "version": "1.0.1"
- }
复制代码
Servers对象
servers数组指定API的目标服务器,可以包含多个环境:
- "servers": [
- {
- "url": "https://api.example.com/{version}",
- "description": "生产服务器",
- "variables": {
- "version": {
- "default": "v1",
- "enum": ["v1", "v2"],
- "description": "API版本"
- }
- }
- },
- {
- "url": "https://dev-api.example.com/v1",
- "description": "开发服务器"
- },
- {
- "url": "https://staging-api.example.com/v1",
- "description": "预发布服务器"
- }
- ]
复制代码
在这个例子中,我们使用服务器变量来支持API版本控制。
Paths对象
paths对象是Swagger JSON的核心,它定义了API的路径和操作。让我们看一个完整的用户管理API示例:
- "paths": {
- "/users": {
- "get": {
- "summary": "获取用户列表",
- "description": "返回系统中的所有用户列表,支持分页和筛选",
- "operationId": "getUsers",
- "tags": ["用户管理"],
- "parameters": [
- {
- "name": "page",
- "in": "query",
- "description": "页码",
- "required": false,
- "schema": {
- "type": "integer",
- "default": 1
- }
- },
- {
- "name": "limit",
- "in": "query",
- "description": "每页记录数",
- "required": false,
- "schema": {
- "type": "integer",
- "default": 20,
- "maximum": 100
- }
- },
- {
- "name": "role",
- "in": "query",
- "description": "按角色筛选",
- "required": false,
- "schema": {
- "type": "string",
- "enum": ["admin", "user", "guest"]
- }
- }
- ],
- "responses": {
- "200": {
- "description": "成功获取用户列表",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "users": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/User"
- }
- },
- "pagination": {
- "$ref": "#/components/schemas/Pagination"
- }
- }
- }
- }
- }
- },
- "401": {
- "description": "未授权"
- },
- "403": {
- "description": "禁止访问"
- }
- },
- "security": [
- {
- "bearerAuth": []
- }
- ]
- },
- "post": {
- "summary": "创建新用户",
- "description": "在系统中创建一个新用户",
- "operationId": "createUser",
- "tags": ["用户管理"],
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/NewUser"
- }
- }
- }
- },
- "responses": {
- "201": {
- "description": "用户创建成功",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/User"
- }
- }
- }
- },
- "400": {
- "description": "无效的输入数据"
- },
- "409": {
- "description": "用户已存在"
- }
- },
- "security": [
- {
- "bearerAuth": []
- }
- ]
- }
- },
- "/users/{userId}": {
- "get": {
- "summary": "获取用户详情",
- "description": "根据用户ID获取用户详细信息",
- "operationId": "getUserById",
- "tags": ["用户管理"],
- "parameters": [
- {
- "name": "userId",
- "in": "path",
- "required": true,
- "description": "用户ID",
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "成功获取用户详情",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/User"
- }
- }
- }
- },
- "404": {
- "description": "用户不存在"
- }
- },
- "security": [
- {
- "bearerAuth": []
- }
- ]
- },
- "put": {
- "summary": "更新用户信息",
- "description": "更新指定用户的信息",
- "operationId": "updateUser",
- "tags": ["用户管理"],
- "parameters": [
- {
- "name": "userId",
- "in": "path",
- "required": true,
- "description": "用户ID",
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- }
- ],
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/UpdateUser"
- }
- }
- }
- },
- "responses": {
- "200": {
- "description": "用户更新成功",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/User"
- }
- }
- }
- },
- "400": {
- "description": "无效的输入数据"
- },
- "404": {
- "description": "用户不存在"
- }
- },
- "security": [
- {
- "bearerAuth": []
- }
- ]
- },
- "delete": {
- "summary": "删除用户",
- "description": "从系统中删除指定用户",
- "operationId": "deleteUser",
- "tags": ["用户管理"],
- "parameters": [
- {
- "name": "userId",
- "in": "path",
- "required": true,
- "description": "用户ID",
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- }
- ],
- "responses": {
- "204": {
- "description": "用户删除成功"
- },
- "404": {
- "description": "用户不存在"
- }
- },
- "security": [
- {
- "bearerAuth": []
- }
- ]
- }
- }
- }
复制代码
这个示例展示了如何定义完整的CRUD操作,包括:
• 路径参数(userId)
• 查询参数(page,limit,role)
• 请求体(用于创建和更新用户)
• 响应定义(包括成功和错误响应)
• 安全要求(使用Bearer认证)
定义数据模型
在Swagger JSON中,数据模型在components.schemas部分定义。这些模型可以被路径和响应引用,确保API文档的一致性和可维护性。
基本数据模型
让我们为用户管理API定义一些基本的数据模型:
- "components": {
- "schemas": {
- "User": {
- "type": "object",
- "required": ["id", "username", "email", "role"],
- "properties": {
- "id": {
- "type": "string",
- "format": "uuid",
- "description": "用户唯一标识符",
- "readOnly": true,
- "example": "550e8400-e29b-41d4-a716-446655440000"
- },
- "username": {
- "type": "string",
- "description": "用户名",
- "minLength": 3,
- "maxLength": 30,
- "pattern": "^[a-zA-Z0-9_-]+$",
- "example": "johndoe"
- },
- "email": {
- "type": "string",
- "format": "email",
- "description": "用户电子邮箱",
- "example": "john.doe@example.com"
- },
- "firstName": {
- "type": "string",
- "description": "名字",
- "example": "John"
- },
- "lastName": {
- "type": "string",
- "description": "姓氏",
- "example": "Doe"
- },
- "role": {
- "type": "string",
- "description": "用户角色",
- "enum": ["admin", "user", "guest"],
- "example": "user"
- },
- "createdAt": {
- "type": "string",
- "format": "date-time",
- "description": "创建时间",
- "readOnly": true,
- "example": "2023-01-01T00:00:00Z"
- },
- "updatedAt": {
- "type": "string",
- "format": "date-time",
- "description": "更新时间",
- "readOnly": true,
- "example": "2023-01-01T00:00:00Z"
- }
- }
- },
- "NewUser": {
- "type": "object",
- "required": ["username", "email", "password"],
- "properties": {
- "username": {
- "type": "string",
- "description": "用户名",
- "minLength": 3,
- "maxLength": 30,
- "pattern": "^[a-zA-Z0-9_-]+$",
- "example": "johndoe"
- },
- "email": {
- "type": "string",
- "format": "email",
- "description": "用户电子邮箱",
- "example": "john.doe@example.com"
- },
- "password": {
- "type": "string",
- "format": "password",
- "description": "密码",
- "minLength": 8,
- "writeOnly": true,
- "example": "SecurePassword123!"
- },
- "firstName": {
- "type": "string",
- "description": "名字",
- "example": "John"
- },
- "lastName": {
- "type": "string",
- "description": "姓氏",
- "example": "Doe"
- }
- }
- },
- "UpdateUser": {
- "type": "object",
- "properties": {
- "email": {
- "type": "string",
- "format": "email",
- "description": "用户电子邮箱",
- "example": "john.doe@example.com"
- },
- "firstName": {
- "type": "string",
- "description": "名字",
- "example": "John"
- },
- "lastName": {
- "type": "string",
- "description": "姓氏",
- "example": "Doe"
- },
- "role": {
- "type": "string",
- "description": "用户角色",
- "enum": ["admin", "user", "guest"],
- "example": "user"
- }
- }
- },
- "Pagination": {
- "type": "object",
- "properties": {
- "page": {
- "type": "integer",
- "description": "当前页码",
- "example": 1
- },
- "limit": {
- "type": "integer",
- "description": "每页记录数",
- "example": 20
- },
- "total": {
- "type": "integer",
- "description": "总记录数",
- "example": 100
- },
- "pages": {
- "type": "integer",
- "description": "总页数",
- "example": 5
- }
- }
- },
- "Error": {
- "type": "object",
- "required": ["code", "message"],
- "properties": {
- "code": {
- "type": "integer",
- "description": "错误代码",
- "example": 400
- },
- "message": {
- "type": "string",
- "description": "错误消息",
- "example": "Invalid input data"
- },
- "details": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "错误详情",
- "example": ["Username is required", "Email must be a valid email address"]
- }
- }
- }
- }
- }
复制代码
这些数据模型展示了Swagger JSON中模式定义的各种特性:
1. 基本类型和格式:如string、integer、date-time、email、uuid等
2. 验证规则:如required、minLength、maxLength、pattern等
3. 枚举值:使用enum限制字段的可能值
4. 只读和只写字段:使用readOnly和writeOnly标记
5. 引用:使用$ref引用其他模式
6. 示例值:使用example提供示例数据
复杂数据模型
对于更复杂的场景,你可以定义嵌套对象、数组、多态类型等。以下是一个示例:
- "components": {
- "schemas": {
- "Order": {
- "type": "object",
- "required": ["id", "customer", "items", "total", "status"],
- "properties": {
- "id": {
- "type": "string",
- "format": "uuid",
- "description": "订单ID",
- "readOnly": true
- },
- "customer": {
- "$ref": "#/components/schemas/Customer"
- },
- "items": {
- "type": "array",
- "description": "订单项目",
- "items": {
- "$ref": "#/components/schemas/OrderItem"
- }
- },
- "shippingAddress": {
- "oneOf": [
- {
- "$ref": "#/components/schemas/Address"
- },
- {
- "type": "null"
- }
- ],
- "description": "配送地址"
- },
- "billingAddress": {
- "$ref": "#/components/schemas/Address"
- },
- "payment": {
- "oneOf": [
- {
- "$ref": "#/components/schemas/CreditCardPayment"
- },
- {
- "$ref": "#/components/schemas/PayPalPayment"
- }
- ],
- "discriminator": {
- "propertyName": "type",
- "mapping": {
- "credit_card": "#/components/schemas/CreditCardPayment",
- "paypal": "#/components/schemas/PayPalPayment"
- }
- }
- },
- "total": {
- "type": "number",
- "format": "decimal",
- "description": "订单总金额",
- "minimum": 0
- },
- "status": {
- "type": "string",
- "description": "订单状态",
- "enum": ["pending", "processing", "shipped", "delivered", "cancelled"],
- "default": "pending"
- },
- "createdAt": {
- "type": "string",
- "format": "date-time",
- "description": "创建时间",
- "readOnly": true
- },
- "updatedAt": {
- "type": "string",
- "format": "date-time",
- "description": "更新时间",
- "readOnly": true
- }
- }
- },
- "OrderItem": {
- "type": "object",
- "required": ["product", "quantity", "price"],
- "properties": {
- "product": {
- "$ref": "#/components/schemas/Product"
- },
- "quantity": {
- "type": "integer",
- "description": "数量",
- "minimum": 1
- },
- "price": {
- "type": "number",
- "format": "decimal",
- "description": "单价",
- "minimum": 0
- }
- }
- },
- "Customer": {
- "type": "object",
- "required": ["id", "name", "email"],
- "properties": {
- "id": {
- "type": "string",
- "format": "uuid",
- "description": "客户ID"
- },
- "name": {
- "type": "string",
- "description": "客户姓名"
- },
- "email": {
- "type": "string",
- "format": "email",
- "description": "客户邮箱"
- },
- "phone": {
- "type": "string",
- "description": "客户电话"
- }
- }
- },
- "Address": {
- "type": "object",
- "required": ["street", "city", "country"],
- "properties": {
- "street": {
- "type": "string",
- "description": "街道地址"
- },
- "city": {
- "type": "string",
- "description": "城市"
- },
- "state": {
- "type": "string",
- "description": "州/省"
- },
- "postalCode": {
- "type": "string",
- "description": "邮政编码"
- },
- "country": {
- "type": "string",
- "description": "国家"
- }
- }
- },
- "CreditCardPayment": {
- "type": "object",
- "required": ["type", "cardNumber", "expiryDate", "cvv"],
- "properties": {
- "type": {
- "type": "string",
- "enum": ["credit_card"]
- },
- "cardNumber": {
- "type": "string",
- "description": "信用卡号",
- "pattern": "^[0-9]{16}$",
- "writeOnly": true
- },
- "expiryDate": {
- "type": "string",
- "description": "有效期",
- "pattern": "^[0-9]{2}/[0-9]{2}$",
- "writeOnly": true
- },
- "cvv": {
- "type": "string",
- "description": "CVV码",
- "pattern": "^[0-9]{3,4}$",
- "writeOnly": true
- },
- "cardholderName": {
- "type": "string",
- "description": "持卡人姓名",
- "writeOnly": true
- }
- }
- },
- "PayPalPayment": {
- "type": "object",
- "required": ["type", "email"],
- "properties": {
- "type": {
- "type": "string",
- "enum": ["paypal"]
- },
- "email": {
- "type": "string",
- "format": "email",
- "description": "PayPal账户邮箱"
- }
- }
- }
- }
- }
复制代码
这个复杂示例展示了:
1. 嵌套对象:Order包含Customer、Address等嵌套对象
2. 数组:Order.items是一个OrderItem对象的数组
3. 多态类型:使用oneOf定义多种可能的类型
4. 判别器:使用discriminator区分多态类型
5. 条件字段:使用oneOf与null类型组合定义可选字段
添加安全配置
API安全是现代应用程序的关键部分。Swagger JSON提供了多种方式来描述API的安全要求。
定义安全方案
在components.securitySchemes部分定义可用的安全方案:
- "components": {
- "securitySchemes": {
- "bearerAuth": {
- "type": "http",
- "scheme": "bearer",
- "bearerFormat": "JWT",
- "description": "JWT Token认证"
- },
- "basicAuth": {
- "type": "http",
- "scheme": "basic",
- "description": "基本认证"
- },
- "apiKey": {
- "type": "apiKey",
- "in": "header",
- "name": "X-API-Key",
- "description": "API密钥认证"
- },
- "oauth2": {
- "type": "oauth2",
- "flows": {
- "authorizationCode": {
- "authorizationUrl": "https://example.com/oauth/authorize",
- "tokenUrl": "https://example.com/oauth/token",
- "scopes": {
- "read": "读取权限",
- "write": "写入权限"
- }
- },
- "implicit": {
- "authorizationUrl": "https://example.com/oauth/authorize",
- "scopes": {
- "read": "读取权限",
- "write": "写入权限"
- }
- },
- "password": {
- "tokenUrl": "https://example.com/oauth/token",
- "scopes": {
- "read": "读取权限",
- "write": "写入权限"
- }
- },
- "clientCredentials": {
- "tokenUrl": "https://example.com/oauth/token",
- "scopes": {
- "read": "读取权限",
- "write": "写入权限"
- }
- }
- }
- }
- }
- }
复制代码
这个示例定义了四种常见的安全方案:
1. Bearer认证:通常用于JWT令牌
2. 基本认证:用户名和密码
3. API密钥:在头部传递的API密钥
4. OAuth2:包括授权码、隐式、密码和客户端凭据流程
应用安全要求
在API操作上应用安全要求:
- "paths": {
- "/users": {
- "get": {
- "summary": "获取用户列表",
- "security": [
- {
- "bearerAuth": []
- },
- {
- "apiKey": []
- }
- ],
- // 其他操作定义...
- },
- "post": {
- "summary": "创建用户",
- "security": [
- {
- "bearerAuth": []
- }
- ],
- // 其他操作定义...
- }
- },
- "/public/info": {
- "get": {
- "summary": "获取公开信息",
- // 没有security属性,表示不需要认证
- // 其他操作定义...
- }
- }
- }
复制代码
在这个示例中:
• /users的GET操作支持Bearer认证或API密钥认证
• /users的POST操作只支持Bearer认证
• /public/info不需要认证
全局安全要求
你还可以在根级别定义全局安全要求,应用于所有API操作:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0"
- },
- "security": [
- {
- "bearerAuth": []
- }
- ],
- "paths": {
- // 路径定义...
- }
- }
复制代码
然后,对于不需要认证的操作,可以使用空数组覆盖全局安全要求:
- "/public/info": {
- "get": {
- "summary": "获取公开信息",
- "security": [],
- // 其他操作定义...
- }
- }
复制代码
高级配置技巧
自定义UI配置
Swagger UI可以通过swagger-ui扩展进行自定义:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0"
- },
- "paths": {},
- "x-swagger-ui": {
- "filter": true,
- "displayRequestDuration": true,
- "docExpansion": "none",
- "defaultModelsExpandDepth": -1,
- "defaultModelExpandDepth": 1,
- "displayOperationId": true,
- "showExtensions": true,
- "showCommonExtensions": true,
- "supportedSubmitMethods": ["get", "post", "put", "delete"],
- "validatorUrl": "https://validator.swagger.io"
- }
- }
复制代码
标签分组
使用标签对API操作进行分组,提高文档的可读性:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0"
- },
- "tags": [
- {
- "name": "用户管理",
- "description": "用户相关的操作"
- },
- {
- "name": "产品管理",
- "description": "产品相关的操作"
- },
- {
- "name": "订单管理",
- "description": "订单相关的操作"
- }
- ],
- "paths": {
- "/users": {
- "get": {
- "tags": ["用户管理"],
- "summary": "获取用户列表",
- // 其他操作定义...
- }
- },
- "/products": {
- "get": {
- "tags": ["产品管理"],
- "summary": "获取产品列表",
- // 其他操作定义...
- }
- },
- "/orders": {
- "get": {
- "tags": ["订单管理"],
- "summary": "获取订单列表",
- // 其他操作定义...
- }
- }
- }
- }
复制代码
外部文档引用
使用externalDocs引用外部文档:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0",
- "externalDocs": {
- "description": "完整文档",
- "url": "https://docs.example.com"
- }
- },
- "paths": {
- "/users": {
- "get": {
- "summary": "获取用户列表",
- "externalDocs": {
- "description": "用户管理指南",
- "url": "https://docs.example.com/user-management"
- },
- // 其他操作定义...
- }
- }
- }
- }
复制代码
示例值和示例请求/响应
为参数、请求体和响应添加示例值:
- "paths": {
- "/users": {
- "post": {
- "summary": "创建用户",
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/NewUser"
- },
- "example": {
- "username": "johndoe",
- "email": "john.doe@example.com",
- "password": "SecurePassword123!",
- "firstName": "John",
- "lastName": "Doe"
- }
- }
- }
- },
- "responses": {
- "201": {
- "description": "用户创建成功",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/User"
- },
- "examples": {
- "successExample": {
- "summary": "成功示例",
- "value": {
- "id": "550e8400-e29b-41d4-a716-446655440000",
- "username": "johndoe",
- "email": "john.doe@example.com",
- "firstName": "John",
- "lastName": "Doe",
- "role": "user",
- "createdAt": "2023-01-01T00:00:00Z",
- "updatedAt": "2023-01-01T00:00:00Z"
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
复制代码
回调定义
对于需要回调的API(如webhooks),可以使用callbacks定义:
- "paths": {
- "/subscriptions": {
- "post": {
- "summary": "创建订阅",
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Subscription"
- }
- }
- }
- },
- "responses": {
- "201": {
- "description": "订阅创建成功"
- }
- },
- "callbacks": {
- "eventCallback": {
- "{$request.body#/callbackUrl}": {
- "post": {
- "summary": "事件回调",
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Event"
- }
- }
- }
- },
- "responses": {
- "200": {
- "description": "回调处理成功"
- }
- }
- }
- }
- }
- }
- }
- }
- }
复制代码
常见问题与解决方案
1. 如何处理版本控制?
问题:随着API的发展,如何处理不同版本的API文档?
解决方案:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0",
- "description": "这是API的v1版本文档。v2版本文档请访问:https://api.example.com/v2/docs"
- },
- "servers": [
- {
- "url": "https://api.example.com/v1",
- "description": "API v1"
- }
- ],
- "paths": {}
- }
复制代码
或者使用服务器变量:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0"
- },
- "servers": [
- {
- "url": "https://api.example.com/{version}",
- "description": "API服务器",
- "variables": {
- "version": {
- "default": "v1",
- "enum": ["v1", "v2"],
- "description": "API版本"
- }
- }
- }
- ],
- "paths": {}
- }
复制代码
2. 如何处理分页?
问题:如何为分页API创建清晰的文档?
解决方案:
- "paths": {
- "/users": {
- "get": {
- "summary": "获取用户列表",
- "parameters": [
- {
- "name": "page",
- "in": "query",
- "description": "页码",
- "required": false,
- "schema": {
- "type": "integer",
- "default": 1,
- "minimum": 1
- }
- },
- {
- "name": "limit",
- "in": "query",
- "description": "每页记录数",
- "required": false,
- "schema": {
- "type": "integer",
- "default": 20,
- "minimum": 1,
- "maximum": 100
- }
- },
- {
- "name": "sort",
- "in": "query",
- "description": "排序字段",
- "required": false,
- "schema": {
- "type": "string",
- "enum": ["id", "username", "email", "createdAt"],
- "default": "id"
- }
- },
- {
- "name": "order",
- "in": "query",
- "description": "排序方向",
- "required": false,
- "schema": {
- "type": "string",
- "enum": ["asc", "desc"],
- "default": "asc"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "成功获取用户列表",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "data": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/User"
- }
- },
- "pagination": {
- "type": "object",
- "properties": {
- "page": {
- "type": "integer",
- "example": 1
- },
- "limit": {
- "type": "integer",
- "example": 20
- },
- "total": {
- "type": "integer",
- "example": 100
- },
- "pages": {
- "type": "integer",
- "example": 5
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
复制代码
3. 如何处理文件上传?
问题:如何为文件上传API创建文档?
解决方案:
- "paths": {
- "/files": {
- "post": {
- "summary": "上传文件",
- "requestBody": {
- "required": true,
- "content": {
- "multipart/form-data": {
- "schema": {
- "type": "object",
- "properties": {
- "file": {
- "type": "string",
- "format": "binary",
- "description": "要上传的文件"
- },
- "description": {
- "type": "string",
- "description": "文件描述"
- },
- "tags": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "文件标签"
- }
- }
- }
- }
- }
- },
- "responses": {
- "201": {
- "description": "文件上传成功",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/File"
- }
- }
- }
- }
- }
- }
- }
- }
复制代码
4. 如何处理错误响应?
问题:如何为API错误创建一致的文档?
解决方案:
首先,定义一个通用的错误响应模式:
- "components": {
- "schemas": {
- "Error": {
- "type": "object",
- "required": ["code", "message"],
- "properties": {
- "code": {
- "type": "integer",
- "description": "错误代码",
- "example": 400
- },
- "message": {
- "type": "string",
- "description": "错误消息",
- "example": "Invalid input data"
- },
- "details": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "错误详情",
- "example": ["Username is required", "Email must be a valid email address"]
- },
- "timestamp": {
- "type": "string",
- "format": "date-time",
- "description": "错误发生时间",
- "readOnly": true
- },
- "path": {
- "type": "string",
- "description": "请求路径",
- "readOnly": true
- }
- }
- }
- }
- }
复制代码
然后,在API操作中引用这个模式:
- "paths": {
- "/users": {
- "post": {
- "summary": "创建用户",
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/NewUser"
- }
- }
- }
- },
- "responses": {
- "201": {
- "description": "用户创建成功",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/User"
- }
- }
- }
- },
- "400": {
- "description": "无效的输入数据",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Error"
- },
- "examples": {
- "validationError": {
- "summary": "验证错误示例",
- "value": {
- "code": 400,
- "message": "Invalid input data",
- "details": [
- "Username is required",
- "Email must be a valid email address"
- ],
- "timestamp": "2023-01-01T00:00:00Z",
- "path": "/users"
- }
- }
- }
- }
- }
- },
- "409": {
- "description": "用户已存在",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Error"
- },
- "examples": {
- "conflictError": {
- "summary": "冲突错误示例",
- "value": {
- "code": 409,
- "message": "User already exists",
- "details": [
- "A user with the same username or email already exists"
- ],
- "timestamp": "2023-01-01T00:00:00Z",
- "path": "/users"
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
复制代码
5. 如何处理复杂查询参数?
问题:如何为带有复杂查询参数的API创建文档?
解决方案:
- "paths": {
- "/users": {
- "get": {
- "summary": "获取用户列表",
- "parameters": [
- {
- "name": "filter",
- "in": "query",
- "description": "筛选条件",
- "required": false,
- "schema": {
- "type": "object",
- "properties": {
- "role": {
- "type": "string",
- "enum": ["admin", "user", "guest"]
- },
- "status": {
- "type": "string",
- "enum": ["active", "inactive", "pending"]
- },
- "createdAt": {
- "type": "object",
- "properties": {
- "from": {
- "type": "string",
- "format": "date-time"
- },
- "to": {
- "type": "string",
- "format": "date-time"
- }
- }
- }
- }
- },
- "example": {
- "role": "user",
- "status": "active",
- "createdAt": {
- "from": "2023-01-01T00:00:00Z",
- "to": "2023-01-31T23:59:59Z"
- }
- }
- },
- {
- "name": "fields",
- "in": "query",
- "description": "返回字段",
- "required": false,
- "schema": {
- "type": "array",
- "items": {
- "type": "string",
- "enum": ["id", "username", "email", "firstName", "lastName", "role", "createdAt"]
- }
- },
- "example": ["id", "username", "email"]
- },
- {
- "name": "include",
- "in": "query",
- "description": "包含关联资源",
- "required": false,
- "schema": {
- "type": "array",
- "items": {
- "type": "string",
- "enum": ["profile", "settings", "permissions"]
- }
- },
- "example": ["profile"]
- }
- ],
- "responses": {
- "200": {
- "description": "成功获取用户列表",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "data": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/User"
- }
- },
- "included": {
- "type": "array",
- "items": {
- "oneOf": [
- {
- "$ref": "#/components/schemas/Profile"
- },
- {
- "$ref": "#/components/schemas/Settings"
- },
- {
- "$ref": "#/components/schemas/Permission"
- }
- ]
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
复制代码
最佳实践
1. 保持一致性
在整个API文档中保持一致的命名约定、结构和格式。例如:
• 使用一致的命名约定(如camelCase或snake_case)
• 为所有错误响应使用相同的结构
• 为所有分页响应使用相同的结构
• 为所有时间字段使用相同的格式
2. 提供清晰的描述
为所有API组件提供清晰、简洁的描述:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "用户管理API",
- "description": "提供用户注册、认证和管理的完整功能。\n\n## 认证\n此API使用Bearer Token(JWT)进行认证。请在请求头中包含`Authorization: Bearer <token>`。\n\n## 错误处理\nAPI使用标准HTTP状态码表示请求的成功或失败。错误响应包含以下结构:\n\n```json\n{\n "code": 400,\n "message": "错误描述",\n "details": ["详细错误信息"],\n "timestamp": "2023-01-01T00:00:00Z",\n "path": "/api/path"\n}\n```",
- "version": "1.0.0"
- }
- }
复制代码
3. 使用示例
为所有参数、请求体和响应提供有意义的示例:
- "components": {
- "schemas": {
- "User": {
- "type": "object",
- "required": ["id", "username", "email"],
- "properties": {
- "id": {
- "type": "string",
- "format": "uuid",
- "description": "用户唯一标识符",
- "example": "550e8400-e29b-41d4-a716-446655440000"
- },
- "username": {
- "type": "string",
- "description": "用户名",
- "minLength": 3,
- "maxLength": 30,
- "example": "johndoe"
- },
- "email": {
- "type": "string",
- "format": "email",
- "description": "用户电子邮箱",
- "example": "john.doe@example.com"
- }
- }
- }
- }
- }
复制代码
4. 使用引用
使用$ref引用重复使用的组件,减少冗余并提高可维护性:
- "components": {
- "schemas": {
- "User": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "format": "uuid"
- },
- "username": {
- "type": "string"
- },
- "email": {
- "type": "string",
- "format": "email"
- }
- }
- },
- "NewUser": {
- "allOf": [
- {
- "type": "object",
- "required": ["username", "email", "password"],
- "properties": {
- "password": {
- "type": "string",
- "format": "password",
- "minLength": 8
- }
- }
- },
- {
- "$ref": "#/components/schemas/User"
- }
- ]
- }
- }
- }
复制代码
5. 验证你的Swagger JSON
使用Swagger编辑器或其他验证工具确保你的Swagger JSON有效:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0"
- },
- "paths": {}
- }
复制代码
6. 使用扩展
使用OpenAPI扩展添加自定义元数据:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "示例API",
- "version": "1.0.0",
- "x-api-id": "12345",
- "x-status": "active",
- "x-contact": {
- "name": "API团队",
- "email": "api@example.com"
- }
- },
- "paths": {
- "/users": {
- "get": {
- "summary": "获取用户列表",
- "x-rate-limit": "100/hour",
- "x-permission": "users:read",
- // 其他操作定义...
- }
- }
- }
- }
复制代码
7. 组织大型API文档
对于大型API,考虑将文档拆分为多个文件,然后使用$ref引用它们:
- {
- "openapi": "3.0.0",
- "info": {
- "title": "大型API",
- "version": "1.0.0"
- },
- "paths": {
- "/users": {
- "$ref": "paths/users.json"
- },
- "/products": {
- "$ref": "paths/products.json"
- },
- "/orders": {
- "$ref": "paths/orders.json"
- }
- },
- "components": {
- "schemas": {
- "User": {
- "$ref": "schemas/User.json"
- },
- "Product": {
- "$ref": "schemas/Product.json"
- },
- "Order": {
- "$ref": "schemas/Order.json"
- }
- },
- "securitySchemes": {
- "bearerAuth": {
- "$ref": "security/bearerAuth.json"
- }
- }
- }
- }
复制代码
总结
通过本教程,我们深入探讨了Swagger JSON配置的各个方面,从基础结构到高级技巧。我们学习了如何:
1. 创建基本的Swagger JSON配置
2. 定义API路径和操作
3. 创建和引用数据模型
4. 实现安全配置
5. 处理常见API场景,如分页、文件上传和错误处理
6. 应用最佳实践来创建专业、可维护的API文档
Swagger JSON配置是创建专业API文档的关键工具。通过遵循本教程中的指南和示例,你可以创建出清晰、全面且易于使用的API文档,帮助开发者快速理解和使用你的API。
记住,好的API文档不仅仅是技术规范,它是开发者与你的服务交互的桥梁。投入时间和精力创建高质量的API文档,将大大提高你的API的采用率和开发者满意度。
现在,你已经掌握了Swagger JSON配置的核心概念和技巧,可以开始创建自己的专业API文档了!
版权声明
1、转载或引用本网站内容(实用Swagger JSON配置教程一步步教你打造专业API文档)须注明原网址及作者(威震华夏关云长),并标明本网站网址(https://pixtech.org/)。
2、对于不当转载或引用本网站内容而引起的民事纷争、行政处理或其他损失,本网站不承担责任。
3、对不遵守本声明或其他违法、恶意使用本网站内容者,本网站保留追究其法律责任的权利。
本文地址: https://pixtech.org/thread-40211-1-1.html
|
|