在 Linux 上使用 Swagger,通常取决于你是 查看/调试 API,还是 生成/开发 API。下面按常见场景给你一套完整说明。
Swagger 现在通常指 OpenAPI + Swagger 工具链:
docker run -p 8080:8080 swaggerapi/swagger-ui
然后浏览器访问:
http://localhost:8080
你可以:
openapi.yaml 或 openapi.jsondocker run -p 8080:8080 \
-v $(pwd)/openapi.yaml:/openapi.yaml \
-e SWAGGER_JSON=/openapi.yaml \
swaggerapi/swagger-ui
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v5.17.14.tar.gz
tar -zxvf v5.17.14.tar.gz
cd swagger-ui-5.17.14/dist
python3 -m http.server 8080
浏览器访问:
http://localhost:8080
修改 swagger-initializer.js 中的 URL 指向你的 API 文档。
docker run -p 8081:8080 swaggerapi/swagger-editor
访问:
http://localhost:8081
适合:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version>
</dependency>
访问:
http://localhost:8080/swagger-ui.html
pip install fastapi uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
启动:
uvicorn main:app --reload
访问:
http://localhost:8000/docs
npm install swagger-ui-express swagger-jsdoc
const express = require("express");
const swaggerJsdoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const app = express();
const spec = swaggerJsdoc({
definition: {
openapi: "3.0.0",
info: { title: "API", version: "1.0.0" }
},
apis: ["./index.js"]
});
app.use("/docs", swaggerUi.serve, swaggerUi.setup(spec));
app.listen(3000);
访问:
http://localhost:3000/docs
wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.46/swagger-codegen-cli-3.0.46.jar
java -jar swagger-codegen-cli-3.0.46.jar
生成前端/后端代码:
java -jar swagger-codegen-cli.jar generate \
-i openapi.yaml \
-l python \
-o ./client
curl 查看 JSON:curl http://localhost:8080/v3/api-docs
| 名称 | 说明 |
|---|---|
| OpenAPI | API 规范 |
| Swagger | 工具实现 |
你可以直接告诉我:
我可以给你 精确到命令级别 的教程。