侧边栏壁纸
博主头像
一朵云的博客博主等级

拥抱生活,向阳而生。

  • 累计撰写 109 篇文章
  • 累计创建 28 个标签
  • 累计收到 7 条评论

目 录CONTENT

文章目录

Swagger API 文档 JSON 格式解读 v3.0

一朵云
2024-04-19 / 0 评论 / 0 点赞 / 2 阅读 / 20204 字

Swagger API 文档 JSON 格式解读 v3.0

前言:

本文也从“简易的用户模块”入手,大致拆解 OpenAPI 3.0(Swagger v3.0)JSON 格式文档的各部分含义,并与之前的 v2.0 作对比,看看有什么优势。

OpenAPI 3.0

image-hhvh.png

{
  "openapi": "3.0.1",
  "info": {
    "title": "用户管理系统 API",
    "description": "一个支持 JWT 认证的用户管理接口文档",
    "version": "1.0.0",
    "contact": {
      "name": "API 支持团队",
      "email": "xxxx@xxxx.com",
      "url": "https://xxxx.com/support"
    },
    "license": {
      "name": "Apache 2.0",
      "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
    }
  },
  "servers": [
    {
      "url": "https://api.xxxx.com/v1",
      "description": "生产环境"
    },
    {
      "url": "https://staging.xxxx.com/v1",
      "description": "测试环境"
    },
    {
      "url": "http://localhost:8080/v1",
      "description": "本地开发"
    }
  ],
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "description": "请输入 Bearer Token,例如:Bearer eyJhbGciOi..."
      }
    },
    "schemas": {
      "User": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int64",
            "example": 123
          },
          "name": {
            "type": "string",
            "example": "张三"
          },
          "email": {
            "type": "string",
            "format": "email",
            "example": "zhangsan@xxxx.com"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "example": "2025-09-06T10:00:00Z"
          }
        },
        "required": ["id", "name", "email"]
      },
      "UserInput": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 2,
            "maxLength": 50
          },
          "email": {
            "type": "string",
            "format": "email"
          },
          "password": {
            "type": "string",
            "minLength": 6
          }
        },
        "required": ["name", "email", "password"]
      },
      "UserListResponse": {
        "type": "object",
        "properties": {
          "data": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/User"
            }
          },
          "total": {
            "type": "integer"
          },
          "page": {
            "type": "integer"
          },
          "limit": {
            "type": "integer"
          }
        }
      }
    },
    "requestBodies": {
      "UserInput": {
        "description": "创建用户时的请求体",
        "required": true,
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/UserInput"
            }
          }
        }
      }
    },
    "responses": {
      "UnauthorizedError": {
        "description": "认证失败",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "message": {
                  "type": "string",
                  "example": "无效的 Token"
                }
              }
            }
          }
        }
      }
    },
    "parameters": {
      "userId": {
        "in": "path",
        "name": "id",
        "required": true,
        "schema": {
          "type": "integer",
          "format": "int64"
        },
        "description": "用户 ID"
      }
    }
  },
  "paths": {
    "/auth/login": {
      "post": {
        "tags": ["认证"],
        "summary": "用户登录",
        "description": "通过邮箱和密码获取 JWT Token",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "email": {
                    "type": "string",
                    "format": "email",
                    "example": "user@xxxx.com"
                  },
                  "password": {
                    "type": "string",
                    "example": "123456"
                  }
                },
                "required": ["email", "password"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "登录成功,返回 Token",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "token": {
                      "type": "string",
                      "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
                    },
                    "expiresIn": {
                      "type": "integer",
                      "example": 3600
                    }
                  },
                  "required": ["token", "expiresIn"]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/UnauthorizedError"
          }
        }
      }
    },
    "/users": {
      "get": {
        "tags": ["用户管理"],
        "summary": "获取用户列表",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "schema": {
              "type": "integer",
              "default": 1
            },
            "description": "页码"
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "default": 10
            },
            "description": "每页数量"
          }
        ],
        "responses": {
          "200": {
            "description": "返回用户列表",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UserListResponse"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": ["用户管理"],
        "summary": "创建新用户",
        "requestBody": {
          "$ref": "#/components/requestBodies/UserInput"
        },
        "responses": {
          "201": {
            "description": "用户创建成功",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/User"
                }
              }
            }
          },
          "400": {
            "description": "参数错误"
          }
        }
      }
    },
    "/users/{id}": {
      "get": {
        "tags": ["用户管理"],
        "summary": "根据 ID 获取用户",
        "parameters": [
          {
            "$ref": "#/components/parameters/userId"
          }
        ],
        "responses": {
          "200": {
            "description": "成功获取用户",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/User"
                }
              }
            }
          },
          "404": {
            "description": "用户不存在"
          }
        }
      }
    }
  }
}

​ 

解读:

大致的结构:

{
  "openapi": "3.0.1",           // 规范版本
  "info": { ... },              // API 基本信息
  "servers": [ ... ],           // 多环境服务器配置
  "components": { ... },        // 可复用组件(模型、参数、响应等)
  "paths": { ... }              // 接口路径定义
}

​ 

1、openapi

表示使用的是 OpenAPI 3.0.1 规范。

​ 

2、info

字段 说明
title API 的名称,显示在 Swagger UI 顶部
description 简要说明,可用于介绍功能、认证方式等
version 当前 API 版本,建议使用语义化版本(如 1.0.0
contact 联系方式,支持 name/email/url
license 开源协议,如 Apache 2.0、MIT 等

​ 

3、servers

定义了 API 在不同环境下的基础 URL,为 Swagger UI 界面提供了一键切换环境的功能。

​ 

4、components

可复用组件(OpenAPI 3.0 最强大的部分),一次定义,多次复用!

​ 

①、securitySchemes

后续所有需要认证的接口都可以引用它,在路径中添加 "security": [ { "bearerAuth": [] } ] 即可启用认证。

​ 

②、schemas

User 模型

"User": {
  "type": "object",
  "properties": {
    "id": { "type": "integer", "format": "int64" },
    "name": { "type": "string" },
    "email": { "type": "string", "format": "email" },
    "createdAt": { "type": "string", "format": "date-time" }
  },
  "required": ["id", "name", "email"]
}
  • 用来定义 User对象。
  • format 提供了额外语义:int64emaildate-time
  • required 指定了必填字段。

​ 

UserInput 模型

"UserInput": {
  "properties": {
    "name": { "minLength": 2, "maxLength": 50 },
    "email": { "format": "email" },
    "password": { "minLength": 6 }
  },
  "required": ["name", "email", "password"]
}
  • 用于创建用户的请求体。
  • 包含字段校验规则(长度、格式),可用于生成校验代码。

​ 

UserListResponse 模型

"UserListResponse": {
  "properties": {
    "data": { "type": "array", "items": { "$ref": "#/components/schemas/User" } },
    "total": { "type": "integer" },
    "page": { "type": "integer" },
    "limit": { "type": "integer" }
  }
}
  • 表示分页查询的响应结构。
  • data 是用户数组,复用 User 模型。
  • 支持分页元信息(total/page/limit)。

备注: 所有 schemas 都可以通过 $ref 被其他地方引用,避免重复定义。

​ 

③、requestBodies

请求体复用

"requestBodies": {
  "UserInput": {
    "description": "创建用户时的请求体",
    "required": true,
    "content": {
      "application/json": {
        "schema": { "$ref": "#/components/schemas/UserInput" }
      }
    }
  }
}
  • UserInput 模型包装成一个完整的请求体。
  • 指定了 content-typeapplication/json
  • 可在多个 POST/PUT 接口中复用。

​ 

④、response

响应复用

"responses": {
  "UnauthorizedError": {
    "description": "认证失败",
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "properties": {
            "message": { "type": "string", "example": "无效的 Token" }
          }
        }
      }
    }
  }
}
  • 定义了一个通用的 401 错误响应
  • 所有需要返回“认证失败”的接口都可以引用它。

​ 

⑤、parameters

参数复用

"parameters": {
  "userId": {
    "in": "path",
    "name": "id",
    "required": true,
    "schema": { "type": "integer", "format": "int64" },
    "description": "用户 ID"
  }
}
  • 定义了一个路径参数 id。(避免每个接口都重复定义 id 参数,提升一致性)
  • 可在多个路径中(如 /users/{id})通过 $ref 引用。

​ 

5、paths

接口的路径地址。

/auth/login 登录接口

"/auth/login": {
  "post": {
    "tags": ["认证"],
    "summary": "用户登录",
    "description": "通过邮箱和密码获取 JWT Token",
    "requestBody": { ... },
    "responses": {
      "200": { ... },
      "401": { "$ref": "#/components/responses/UnauthorizedError" }
    }
  }
}
  • 方法:POST
  • 用途:登录,返回 JWT Token
  • 请求体:包含 emailpassword
  • 响应
    • 200:成功,返回 tokenexpiresIn
    • 401:失败,引用通用错误响应

​ 

/users 获取用户列表

"get": {
  "parameters": [
    { "name": "page", "in": "query", "schema": { "type": "integer", "default": 1 } },
    { "name": "limit", "in": "query", "schema": { "type": "integer", "default": 10 } }
  ],
  "responses": {
    "200": {
      "content": {
        "application/json": {
          "schema": { "$ref": "#/components/schemas/UserListResponse" }
        }
      }
    }
  }
}
  • 方法:POST
  • 支持分页查询(pagelimit
  • 响应复用 UserListResponse 模型
  • 示例完整,便于前端调试

​ 

/users 创建用户

"post": {
  "requestBody": {
    "$ref": "#/components/requestBodies/UserInput"
  },
  "responses": {
    "201": {
      "content": {
        "application/json": {
          "schema": { "$ref": "#/components/schemas/User" }
        }
      }
    }
  }
}
  • 请求体复用 UserInput
  • 成功状态码为 201 Created(符合 RESTful 规范)
  • 返回创建后的用户信息(含 id

​ 

/users/{id} 根据 ID 查询用户

"/users/{id}": {
  "get": {
    "parameters": [
      { "$ref": "#/components/parameters/userId" }
    ],
    "responses": {
      "200": {
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/User" }
          }
        }
      },
      "404": { "description": "用户不存在" }
    }
  }
}
  • 使用 userId 参数复用
  • 正确使用 404 表示资源不存在
  • 响应返回完整的 User 对象

​ 

对比:

组件复用能力:从“只能复用模型”到“万物皆可复用”,升级 v3.0 后,可读性高了不少,更好维护了。

类型 2.0 3.0
数据模型 definitions components.schemas
请求体 ❌ 无法复用 components.requestBodies
响应 ❌ 无法复用 components.responses
参数 ❌ 无法复用 components.parameters
安全方案 securityDefinitions components.securitySchemes
0

评论区