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

拥抱生活,向阳而生。

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

目 录CONTENT

文章目录

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

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

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

前言:

本文将从“简易的用户模块”入手,大致拆解 Swagger 2.0 JSON 格式文档的各部分含义。

由于 OpenAPI 3.0 和 2.0(即 Swagger 2.0)之间的区别非常大,虽然它们的目标都是描述 RESTful API,但 3.0 是一次重大重构和升级,引入了许多新特性、更清晰的结构和更强的表达能力。

我们分别基于 2.0 和 3.0 的结构说明下。

备注:其实从 3.0 开始,Swagger 正式更名为 OpenAPI Specification,但还是更习惯叫它 Swagger!

​ 

Swagger 2.0

UI 界面大概长这样,这段json包含了下面这两个分组,共计4个接口。

image-akcy.png

​ 

json文件:

{
  "swagger": "2.0",
  "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"
    }
  },
  "host": "api.xxxx.com",
  "basePath": "/v1",
  "schemes": ["https"],
  "consumes": ["application/json"],
  "produces": ["application/json"],
  
  "tags": [
    {
      "name": "用户管理",
      "description": "增删改查用户信息"
    },
    {
      "name": "认证",
      "description": "登录、注册、获取 Token"
    }
  ],

  "securityDefinitions": {
    "bearerAuth": {
      "type": "apiKey",
      "name": "Authorization",
      "in": "header",
      "description": "Bearer abcdef123456"
    }
  },

  "security": [
    {
      "bearerAuth": []
    }
  ],

  "paths": {
    "/auth/login": {
      "post": {
        "tags": ["认证"],
        "summary": "用户登录",
        "description": "通过邮箱和密码获取 JWT Token",
        "operationId": "loginUser",
        "parameters": [
          {
            "in": "body",
            "name": "credentials",
            "description": "登录凭证",
            "required": true,
            "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",
            "schema": {
              "type": "object",
              "properties": {
                "token": {
                  "type": "string",
                  "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xxxxx"
                },
                "expiresIn": {
                  "type": "integer",
                  "format": "int32",
                  "example": 3600
                }
              },
              "required": ["token", "expiresIn"]
            }
          },
          "401": {
            "description": "邮箱或密码错误"
          }
        }
      }
    },

    "/users": {
      "get": {
        "tags": ["用户管理"],
        "summary": "获取用户列表",
        "description": "分页查询所有用户",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "页码",
            "required": false,
            "type": "integer",
            "default": 1
          },
          {
            "name": "limit",
            "in": "query",
            "description": "每页数量",
            "required": false,
            "type": "integer",
            "default": 10
          }
        ],
        "responses": {
          "200": {
            "description": "返回用户列表",
            "schema": {
              "$ref": "#/definitions/UserListResponse"
            }
          }
        }
      },
      "post": {
        "tags": ["用户管理"],
        "summary": "创建新用户",
        "description": "管理员创建新用户",
        "parameters": [
          {
            "in": "body",
            "name": "user",
            "description": "用户信息",
            "required": true,
            "schema": {
              "$ref": "#/definitions/UserInput"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "用户创建成功",
            "schema": {
              "$ref": "#/definitions/User"
            }
          },
          "400": {
            "description": "参数错误"
          }
        }
      }
    },

    "/users/{id}": {
      "get": {
        "tags": ["用户管理"],
        "summary": "根据 ID 获取用户",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "description": "用户 ID",
            "required": true,
            "type": "integer",
            "format": "int64"
          }
        ],
        "responses": {
          "200": {
            "description": "成功获取用户",
            "schema": {
              "$ref": "#/definitions/User"
            }
          },
          "404": {
            "description": "用户不存在"
          }
        }
      }
    }
  },

  "definitions": {
    "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": "#/definitions/User"
          }
        },
        "total": {
          "type": "integer"
        },
        "page": {
          "type": "integer"
        },
        "limit": {
          "type": "integer"
        }
      }
    }
  }
}

解读:

大致结构:

{
  "swagger": "2.0",             // 规范版本
  "info": { ... },              // API 基本信息
  "host": "...",                // 主机地址
  "basePath": "/v1",            // 公共路径前缀
  "schemes": ["https"],         // 协议
  "consumes/produces": [...],   // 默认数据格式
  "tags": [...],                // 接口分组
  "securityDefinitions": {...}, // 认证方式
  "security": [...],            // 全局认证要求
  "paths": { ... },             // 所有接口路径
  "definitions": { ... }        // 可复用的数据模型
}

1、swagger

"2.0" 声明使用的是 Swagger 2.0 规范(即 OpenAPI 2.0)。

​ 

2、info

主要包含了 API 的元信息:

字段 含义
title 文档标题,显示在 Swagger UI 顶部
description 简要说明,帮助使用者理解用途
version API 版本号,建议与 basePath 一致(如 /v1
contact 联系方式,出问题时可联系团队
license 使用许可,这里是 Apache 2.0(允许商用、修改)

​ 

3、host

API 的域名地址。

​ 

4、basePath

所有接口的公共路径前缀。

​ 

5、schemes

支持的接口协议,如:https

​ 

6、consumes 和 produces

字段 含义
consumes 默认请求体格式是 JSON(POST/PUT 时)
produces 默认响应体格式是 JSON

​ 

7、tags

用于接口分组展示,我这里分了2个组:“用户管理”和“认证”,文档展示更清晰,方便协作时定位问题。

​ 

8、securityDefinitions

用来申明接口认证方式,如:JWT token认证

​ 

9、security

表示所有接口都需要 bearerAuth 认证,如果只想部分接口需要认证,可以不写全局 security

​ 

10、paths

post请求:

"/auth/login": {
  "post": {
    "tags": ["认证"],
    "summary": "用户登录",
    "description": "通过邮箱和密码获取 JWT Token",
    "operationId": "loginUser",
    "parameters": [ ... ],
    "responses": { ... }
  }
}
parameters:请求参数
{
  "in": "body",
  "name": "credentials",
  "required": true,
  "schema": {
    "type": "object",
    "properties": {
      "email": { "type": "string", "format": "email" },
      "password": { "type": "string" }
    },
    "required": ["email", "password"]
  }
}
  • in: body:参数在请求体中(JSON 格式)
  • schema:定义了 JSON 结构
  • required:必填字段
responses:响应参数
  • 200:成功,返回 tokenexpiresIn(过期时间,秒)
  • 401:失败,邮箱或密码错误

get请求:

"/users": {
	"get": {
		"tags": ["用户管理"],
		"summary": "获取用户列表",
		"description": "分页查询所有用户",
		"parameters": [{
				"name": "page",
				"in": "query",
				"description": "页码",
				"required": false,
				"type": "integer",
				"default": 1
			},
			{
				"name": "limit",
				"in": "query",
				"description": "每页数量",
				"required": false,
				"type": "integer",
				"default": 10
			}
		],
		"responses": {
			"200": {
				"description": "返回用户列表",
				"schema": {
					"$ref": "#/definitions/UserListResponse"
				}
			}
		}
	}
}
parameters:请求参数
  • in: query:参数在 URL 中,如:/v1/users?page=1&limit=10
  • 响应使用 UserListResponse 模型(见下文)
"/users/{id}": {
	"get": {
		"tags": ["用户管理"],
		"summary": "根据 ID 获取用户",
		"parameters": [{
			"name": "id",
			"in": "path",
			"description": "用户 ID",
			"required": true,
			"type": "integer",
			"format": "int64"
		}],
		"responses": {
			"200": {
				"description": "成功获取用户",
				"schema": {
					"$ref": "#/definitions/User"
				}
			},
			"404": {
				"description": "用户不存在"
			}
		}
	}
}
parameters:请求参数
  • in: path:参数是路径变量
  • 响应使用 User 模型(见下文)

​ 

11、definitions

可复用数据模型**(Swagger 的核心设计思想:模型复用)**

User

用户完整信息(响应用)

{
  "type": "object",
  "properties": {
    "id": "integer",
    "name": "string",
    "email": "string",
    "createdAt": "date-time"
  },
  "required": ["id", "name", "email"]
}

format: date-time 表示 ISO 8601 时间格式。

UserInput

创建用户时的输入,包含校验规则,前端可据此做表单验证。

{
  "properties": {
    "name": { "minLength": 2, "maxLength": 50 },
    "email": { "format": "email" },
    "password": { "minLength": 6 }
  },
  "required": ["name", "email", "password"]
}

UserListResponse

分页响应结构

{
  "properties": {
    "data": { "type": "array", "items": { "$ref": "#/definitions/User" } },
    "total": "integer",
    "page": "integer",
    "limit": "integer"
  }
}
  • data[]:用户列表数组
  • total:总条数,用于分页
0

评论区