Ubuntu环境下搭建Swagger项目的完整步骤
在开始搭建前,需确保Ubuntu系统已安装以下工具:
yamljs):用于解析Swagger文档(YAML格式)。通过以下命令安装:
# 更新包列表
sudo apt update
# 安装Node.js(选择LTS版本,如14.x)和npm
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt install -y nodejs
# 验证安装
node -v # 应输出Node.js版本(如v14.x.x)
npm -v # 应输出npm版本(如6.x.x)
注:若需使用Docker部署,还需安装Docker(
sudo apt install docker.io)。
新建一个专用目录用于存放项目文件,并进入该目录:
mkdir swagger-demo && cd swagger-demo
通过npm init命令创建项目配置文件(package.json),记录项目依赖与脚本:
npm init -y # 使用默认配置快速初始化
安装swagger-ui-express(用于将Swagger UI集成到Express应用)和yamljs(用于解析YAML格式的Swagger文档):
npm install swagger-ui-express yamljs --save
在项目根目录创建swagger.yaml文件,定义API的接口规范(包括路径、参数、响应等)。以下是一个简单的用户管理API示例:
swagger: '2.0'
info:
title: Sample API
description: A demo API for Swagger on Ubuntu
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
format: int64
name:
type: string
email:
type: string
format: email
在项目根目录创建app.js文件,编写Express服务器代码,集成Swagger UI:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// 加载Swagger文档
const swaggerDocument = YAML.load('./swagger.yaml');
// 初始化Express应用
const app = express();
// 集成Swagger UI,挂载到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 启动服务器(默认端口3000,可通过环境变量修改)
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Swagger UI is running at http://localhost:${PORT}/api-docs`);
});
在项目目录下运行以下命令,启动Express服务器:
node app.js
启动后,在浏览器中访问http://localhost:3000/api-docs,即可看到Swagger UI界面,展示定义的API文档。
若希望避免本地环境依赖,可使用Docker部署Swagger项目:
Dockerfile,定义镜像构建步骤:FROM node:14
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
docker build -t swagger-ui-demo .
docker run -p 3000:3000 swagger-ui-demo
访问http://localhost:3000/api-docs即可查看Swagger UI。若需限制Swagger UI的访问权限,可通过以下方式增强安全性:
express-basic-auth等库,要求用户输入用户名/密码才能访问/api-docs路径;letsencrypt申请免费SSL证书,通过express-sslify中间件强制HTTPS访问。