在 Linux 环境下生成 Swagger 文档(现在多指 OpenAPI 文档),常见做法取决于你使用的后端语言/框架。下面按最主流场景给你一个清晰指南。
| 场景 | 方式 |
|---|---|
| Spring Boot (Java) | springdoc / swagger-ui |
| Go | swaggo |
| Python (FastAPI) | 自动生成 |
| Python (Flask) | flasgger / apispec |
| 手动编写 | YAML / JSON |
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version>
</dependency>
mvn spring-boot:run
http://localhost:8080/swagger-ui.html
curl http://localhost:8080/v3/api-docs > openapi.json
go install github.com/swaggo/swag/cmd/swag@latest
// @title My API
// @version 1.0
// @BasePath /api
swag init
生成目录:
docs/
├── docs.go
├── swagger.json
└── swagger.yaml
http://localhost:8080/swagger/index.html
from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
def read_items():
return [{"id": 1}]
启动:
uvicorn main:app --reload
文档自动生成:
http://localhost:8000/docs
导出:
http://localhost:8000/openapi.json
openapi: 3.0.0
info:
title: Demo API
version: 1.0.0
paths:
/ping:
get:
responses:
'200':
description: OK
生成 HTML:
npm i -g swagger-cli
swagger-cli validate swagger.yaml
或使用:
npx redoc-cli build swagger.yaml
# 格式化 JSON
jq . openapi.json
# 启动静态文档
python3 -m http.server 8000
为了给你最准确方案,你可以补充:
我可以直接给你可复制的命令。