在 Linux 环境下生成 Swagger 文档,通常取决于你使用的后端语言/框架。下面按常见场景给你总结几种最实用的方式。
依赖(Maven)
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version>
</dependency>
启动后访问
http://localhost:8080/swagger-ui.html
生成静态 JSON
curl http://localhost:8080/v3/api-docs > openapi.json
生成 HTML / PDF(可选)
npm install -g redoc-cli
redoc-cli build openapi.json -o api.html
go install github.com/swaggo/swag/cmd/swag@latest
项目中写注释
// @title My API
// @version 1.0
// @BasePath /api
生成文档
swag init
访问
http://localhost:8080/swagger/index.html
from fastapi import FastAPI
app = FastAPI()
访问:
http://localhost:8000/docs
导出 OpenAPI:
http://localhost:8000/openapi.json
pip install flasgger
npm install swagger-jsdoc swagger-ui-express
const swaggerUi = require('swagger-ui-express');
const swaggerDocs = require('./swagger');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
访问:
http://localhost:3000/api-docs
如果你已经有 openapi.yaml / json:
# 安装
npm install -g redoc-cli
# 生成 HTML
redoc-cli build openapi.yaml -o doc.html
# 生成 PDF
redoc-cli build openapi.yaml -o doc.pdf
# 启动服务
java -jar app.jar
# 获取文档
curl http://localhost:8080/v3/api-docs > openapi.json
# 查看
xdg-open doc.html
我可以直接给你可复制的完整示例。