Swagger 教程
Swagger 解决什么问题、OpenAPI 与它的关系,以及一份最小可用的接口描述文件。
Key PointsSwagger 是一套围绕 OpenAPI 规范的工具链:用一份 YAML/JSON 描述接口,再自动生成文档、调试台和客户端代码。
它解决什么问题
Hand-written API docs rot, drift from the code, and leave field meanings ambiguous. Swagger's answer is to make the API description a machine-readable file (the OpenAPI spec) and generate docs, a try-it console and SDKs from it — change once, everything follows.
Swagger 与 OpenAPI 的关系
| What it is | Note | |
|---|---|---|
| OpenAPI Specification | The spec format (YAML/JSON) | Since 3.0 the name is vendor-neutral |
| Swagger | The tooling family around it | Editor / UI / Codegen |
| Swagger 2.0 | The old spec name | Upgrade to OpenAPI 3.0 |
一份最小的描述文件
YAML
openapi: 3.0.3
info:
title: User API
version: 1.0.0
paths:
/users/{id}:
get:
summary: 查询单个用户
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
'200':
description: 成功
content:
application/json:
schema:
type: object
properties:
id:
type: integer
name:
type: stringDrop this into the Swagger Editor and you get an interactive doc: input boxes for parameters, response examples, and a working try-it button. No front-end code needed.
典型工作流
- Describe — write or generate
openapi.yaml - Validate & lint — catch broken refs and style issues in CI
- Publish — serve Swagger UI / Redoc from the spec
- Consume — generate clients, mock servers, contract tests
The deliverable is the spec file, not the rendered page. Keep
openapi.yaml in the repo, review it, version it — that is what keeps docs from rotting.它解决什么问题
手写接口文档的三个老问题:写完就过期、和代码不一致、对方看不懂字段含义。Swagger 的思路是把接口描述变成一份机器可读的文件(OpenAPI 规范),文档、调试台、SDK 都从这一份文件生成——改一处,全部同步。
Swagger 与 OpenAPI 的关系
| 是什么 | 说明 | |
|---|---|---|
| OpenAPI 规范 | 规范格式本身(YAML/JSON) | 3.0 起改名,厂商中立 |
| Swagger | 围绕它的工具家族 | 编辑器 / UI / 代码生成 |
| Swagger 2.0 | 旧版规范名 | 建议升级到 3.0 |
一份最小的描述文件
YAML
openapi: 3.0.3
info:
title: User API
version: 1.0.0
paths:
/users/{id}:
get:
summary: 查询单个用户
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
'200':
description: 成功
content:
application/json:
schema:
type: object
properties:
id:
type: integer
name:
type: string这份文件放进 Swagger Editor 立刻得到一份可交互文档:参数有输入框,响应有示例,还能直接发请求。不需要写一行前端代码。
典型工作流
- 描述 —— 手写或由代码生成
openapi.yaml - 校验 —— 在 CI 里检查引用与规范问题
- 发布 —— 用 Swagger UI / Redoc 渲染
- 消费 —— 生成客户端、mock 服务、契约测试
文档不是交付物,规范文件才是。把
openapi.yaml 当成代码一样进仓库、走评审、做版本管理,文档才不会过期。