在 Linux 上利用 Swagger 进行 API 数据模型设计
一 环境准备与工具选型
sudo apt update && sudo apt install -y nodejs npmwget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.50.0.tar.gz && tar -xvf swagger-editor-3.50.0.tar.gz && cd swagger-editor-3.50.0 && npm install && npm run startwget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.50.0.tar.gz && tar -xvf swagger-ui-3.50.0.tar.gz && cd swagger-ui-3.50.0 && npm install && npm run startdocker run -d -p 8080:8080 swaggerapi/swagger-editor:v4.6.0docker run -d -p 8081:8080 swaggerapi/swagger-ui:v4.15.5二 设计数据模型的核心步骤
openapi.yamlopenapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: 获取用户列表
responses:
'200':
description: 用户列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
post:
summary: 创建用户
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
'201':
description: 创建成功
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: 请求参数错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
User:
type: object
required:
- id
- name
- email
properties:
id:
type: integer
format: int64
example: 1
name:
type: string
example: Alice
email:
type: string
format: email
example: alice@example.com
createdAt:
type: string
format: date-time
example: 2025-12-23T10:00:00Z
CreateUserRequest:
type: object
required:
- name
- email
properties:
name:
type: string
minLength: 1
example: Bob
email:
type: string
format: email
example: bob@example.com
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
example: 400
message:
type: string
example: Invalid input
三 将模型集成到 Node Express 服务
npm install -D swagger-jsdoc swagger-ui-expressserver.js):const express = require('express');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const swaggerOptions = {
swaggerDefinition: {
openapi: '3.0.0',
info: { title: 'Sample API', version: '1.0.0' },
servers: [{ url: 'http://localhost:3000' }]
},
apis: ['./openapi.yaml'] // 指向你的 OpenAPI 文件
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
app.get('/users', (req, res) => {
res.json([
{ id: 1, name: 'Alice', email: 'alice@example.com', createdAt: '2025-12-23T10:00:00Z' }
]);
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
node server.js,访问 http://localhost:3000/api-docs 查看交互式文档。四 进阶 模型校验与代码生成
const Joi = require('joi');
const createUserSchema = Joi.object({
name: Joi.string().min(1).required(),
email: Joi.string().email().required()
});
app.post('/users', (req, res, next) => {
const { error } = createUserSchema.validate(req.body);
if (error) return res.status(400).json({ message: error.details[0].message });
next();
}, (req, res) => {
// 处理创建逻辑
res.status(201).json({ id: 2, ...req.body, createdAt: new Date().toISOString() });
});