Swagger 教程

Swagger 解决什么问题、OpenAPI 与它的关系,以及一份最小可用的接口描述文件。

Beginner
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 isNote
OpenAPI SpecificationThe spec format (YAML/JSON)Since 3.0 the name is vendor-neutral
SwaggerThe tooling family around itEditor / UI / Codegen
Swagger 2.0The old spec nameUpgrade 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: string

Drop 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.

典型工作流

  1. Describe — write or generate openapi.yaml
  2. Validate & lint — catch broken refs and style issues in CI
  3. Publish — serve Swagger UI / Redoc from the spec
  4. 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.

Friends & Partners