在 Linux 环境下编写 Swagger(OpenAPI)文档,通常有三种常见方式:
下面按「从零开始」的思路说明。
# 安装 node(用于 swagger-cli / editor)
sudo apt update
sudo apt install -y nodejs npm
# 安装 swagger-cli
sudo npm install -g swagger-cli
# 可选:安装 yaml 工具
sudo apt install -y yamllint
mkdir swagger-demo && cd swagger-demo
touch swagger.yaml
swagger.yamlopenapi: 3.0.3
info:
title: User API
version: 1.0.0
description: Linux 环境下编写的 Swagger 文档示例
servers:
- url: http://localhost:8080/api
paths:
/users:
get:
summary: 获取用户列表
responses:
'200':
description: 成功
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
/users/{id}:
get:
summary: 根据ID获取用户
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
swagger-cli validate swagger.yaml
输出:
swagger.yaml is valid
docker run -d -p 8081:8080 swaggerapi/swagger-editor
浏览器访问:
http://localhost:8081
docker run -d -p 8080:8080 \
-e SWAGGER_JSON=/swagger.yaml \
-v $PWD/swagger.yaml:/swagger.yaml \
swaggerapi/swagger-ui
go install github.com/swaggo/swag/cmd/swag@latest
swag init
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
from fastapi import FastAPI
app = FastAPI()
@app.get("/users")
def read_users():
return []
自动生成:
http://localhost:8000/docs
✅ 使用 YAML 而非 JSON(更易维护)
✅ 将 Swagger 文件纳入 Git 管理
✅ CI 中加 swagger-cli validate
✅ 接口变更先改文档,再改代码
如果你告诉我:
我可以给你更具体的示例。