Swagger UI 与文档发布
把规范渲染成可交互文档:静态托管、Docker、服务内嵌三种方式。
Key PointsSwagger UI 是一个纯前端页面,只要给它一个规范 URL 就能渲染;发布方式取决于你想让谁访问。
三种发布方式
| Way | Who can reach it | Best for |
|---|---|---|
| In-app endpoint | Anyone who can reach the service | Internal teams |
| Static hosting | Public | Open API docs |
| Docker / self-host | Whatever you expose | Air-gapped / on-prem |
服务内嵌(Spring Boot)
With springdoc, /swagger-ui.html is the UI and /v3/api-docs is the spec itself. In production you usually disable the UI and keep only the spec for gateways or internal tooling.
YAML
# application.yml
springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
enabled: false # 生产关掉 UI静态托管
Put openapi.yaml and the Swagger UI dist on any static server; the page only needs a url pointing at the spec.
Bash
npm i swagger-ui-dist
cp -r node_modules/swagger-ui-dist/* public/docs/
cp openapi.yaml public/docs/
# public/docs/index.html 里改成:
# url: "./openapi.yaml"Docker 自托管
Bash
docker run -d --name swagger-ui -p 8080:8080 \
-e URL=https://api.example.com/v1/openapi.yaml \
swaggerapi/swagger-uiBefore publishing, strip internal hostnames, test accounts and internal field names. Whatever sits in
servers — including http://10.x.x.x — shows up in the docs and the try-it console.用 Redoc 做只读文档
Redoc uses a three-column layout (nav, body, samples) and reads better for external audiences; Swagger UI is better for hands-on testing. Both read the same spec.
HTML
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
<redoc spec-url="./openapi.yaml"></redoc>三种发布方式
| 方式 | 谁能访问 | 适合 |
|---|---|---|
| 服务内嵌 | 能访问服务的人 | 内部团队 |
| 静态托管 | 公开 | 对外开放文档 |
| Docker 自托管 | 取决于你的暴露范围 | 内网、私有化 |
服务内嵌(Spring Boot)
引入 springdoc 后,/swagger-ui.html 是 UI,/v3/api-docs 是规范本体。生产环境通常关掉 UI,只保留规范给网关或内部工具读。
YAML
# application.yml
springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
enabled: false # 生产关掉 UI静态托管
把 openapi.yaml 和 Swagger UI 的 dist 一起放到任意静态服务器上。前端只需要一个 url 指向规范文件。
Bash
npm i swagger-ui-dist
cp -r node_modules/swagger-ui-dist/* public/docs/
cp openapi.yaml public/docs/
# public/docs/index.html 里改成:
# url: "./openapi.yaml"Docker 自托管
Bash
docker run -d --name swagger-ui -p 8080:8080 \
-e URL=https://api.example.com/v1/openapi.yaml \
swaggerapi/swagger-ui对外发布前先确认规范里没有内网地址、测试账号、内部字段名。
servers 里的 http://10.x.x.x 会原样出现在文档和「试一试」里。用 Redoc 做只读文档
Redoc 用三栏布局,左侧目录、中间正文、右侧示例,适合对外阅读;Swagger UI 更适合自己调试。两者可以读同一份规范。
HTML
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
<redoc spec-url="./openapi.yaml"></redoc>