在 Debian 上编写 Swagger API 文档的实操指南
一 准备环境与工具
sudo apt update && sudo apt install -y nodejs npmswagger-editor-dist,通过 npx 启动;http-server)托管 dist 目录并在浏览器访问。sudo npm install -g swagger-jsdoc swagger-ui-express二 编写规范文件
openapi 与 info(标题、描述、版本)servers(多环境地址)paths(路径与方法,含参数、请求体、响应)components(可复用的 schemas、parameters、responses、securitySchemes)openapi: 3.0.3
info:
title: 示例 API
description: 在 Debian 上编写的示例 API 文档
version: 1.0.0
servers:
- url: http://localhost:3000
description: 本地开发环境
paths:
/users:
get:
summary: 获取用户列表
parameters:
- name: page
in: query
required: false
schema:
type: integer
minimum: 1
default: 1
responses:
'200':
description: 成功返回用户列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
/users/{id}:
get:
summary: 获取单个用户
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
responses:
'200':
description: 成功返回用户
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: 用户不存在
components:
schemas:
User:
type: object
required:
- id
- username
properties:
id:
type: string
format: uuid
example: 550e8400-e29b-41d4-a716-446655440000
username:
type: string
minLength: 3
example: alice
email:
type: string
format: email
example: alice@example.com
swagger: "2.0"、host、basePath、schemes、paths、definitions、securityDefinitions 等,结构略有差异。三 本地预览与校验
npm i swagger-ui-expressconst express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./openapi.yaml'); // 或 .json
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => console.log('Docs at http://localhost:3000/api-docs'));
http://localhost:3000/api-docsnpm i --save-dev swagger-jsdoc// swagger.js
const swaggerJsdoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: { title: 'API', version: '1.0.0' },
servers: [{ url: 'http://localhost:3000' }]
},
apis: ['./routes/*.js'] // 扫描含注释的路由文件
};
const spec = swaggerJsdoc(options);
console.log(JSON.stringify(spec, null, 2));
swagger-ui-express 即可预览。四 最佳实践与常见要点
$ref)。components.securitySchemes 定义并在全局或操作级应用。