Ubuntu上集成Swagger(OpenAPI)的常见步骤
在集成Swagger前,需确保Ubuntu系统安装了Node.js、npm(Node包管理器)和Java(部分工具链需要)。
sudo apt update
sudo apt install -y nodejs npm
验证安装:node -v(显示版本号)、npm -v(显示版本号)。sudo apt install -y openjdk-11-jdk
验证安装:java -version(显示Java版本信息)。根据集成方式选择工具:
sudo npm install -g swagger-ui-express # 全局安装
# 或在项目中本地安装(推荐)
cd your-project
npm install swagger-ui-express --save-dev
sudo apt install -y docker.io # 安装Docker
sudo systemctl start docker # 启动Docker服务
sudo systemctl enable docker # 设置开机自启
docker pull swaggerapi/swagger-ui-express # 拉取镜像
Swagger文档通常用swagger.yaml(YAML格式)或swagger.json(JSON格式)定义。
swagger.yaml文件:swagger.yaml,内容如下(以Express API为例):swagger: '2.0'
info:
title: Sample API
description: A demo API for Swagger integration
version: '1.0.0'
host: localhost:3000
basePath: /api
schemes:
- http
paths:
/users:
get:
summary: Get all users
responses:
'200':
description: A list of users
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
name:
type: string
可使用Swagger Editor(在线或本地)编辑并生成文档。若项目基于Express框架,可通过swagger-ui-express中间件集成Swagger UI。
app.js),添加以下代码:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs'); // 用于解析YAML文件
const app = express();
// 加载Swagger文档
const swaggerDocument = YAML.load('./swagger.yaml');
// 集成Swagger UI到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 其他路由和中间件
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});
npm install express yamljs --save
node app.js
node app.js;若使用Docker,运行docker run -p 8080:8080 swaggerapi/swagger-ui-express。http://localhost:3000/api-docs(Node.js)或http://localhost:8080(Docker),即可看到Swagger UI界面,包含API文档和测试功能。若需隔离环境,可使用Docker Compose部署Express+Swagger:
Dockerfile:FROM node:14
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
docker-compose.yml:version: '3'
services:
app:
build: .
ports:
- "3000:3000"
volumes:
- .:/usr/src/app
docker-compose up --build
访问http://localhost:3000/api-docs即可。