Swagger 核心组件

Editor、UI、Codegen、Hub 各自做什么,以及 Java/Spring 生态里的 springdoc。

Beginner
Key PointsEditor 写规范、UI 渲染文档、Codegen 生成代码、Hub 托管规范;Spring 项目用 springdoc 从注解直接产出规范。

四个核心工具

ToolJobTypical use
Swagger EditorWrite & validate the specBrowser IDE with live preview
Swagger UIRender the spec as a doc site/swagger-ui in your service
Swagger CodegenGenerate clients and serversCI job, or openapi-generator
Swagger HubHost, version and collaborateTeam design-first workflow

本地跑一个 Editor

Bash
docker run -d -p 8080:8080 \
  -e SWAGGER_JSON=/spec/openapi.yaml \
  -v "$PWD:/spec" \
  swaggerapi/swagger-ui

# 打开 http://localhost:8080

Java / Spring 生态:springdoc

Spring Boot projects rarely hand-write YAML: annotations describe the API and springdoc generates /v3/api-docs at runtime, which Swagger UI reads. The spec cannot drift from the code.

XML
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.6.0</version>
</dependency>
Java
@Operation(summary = "查询单个用户")
@GetMapping("/users/{id}")
public User get(@Parameter(description = "用户 ID") @PathVariable Long id) {
    return userService.get(id);
}
The Swagger 2 era springfox is unmaintained; use springdoc-openapi for new projects. Their annotations are not interchangeable, so migrate them together.

其他语言的一行接入

  • Python / FastAPI — app = FastAPI(),/docs 自动可用
  • Node.js / Express — swagger-ui-express + swagger-jsdoc
  • Go — swag init 从注释生成 docs/,再挂 gin-swagger
  • PHP / Laravel — l5-swagger 读注解生成

Friends & Partners