1. 安装Swagger工具
在Ubuntu上配置Swagger前,需先安装相关工具。若使用Node.js环境(推荐),先确保已安装Node.js和npm:
sudo apt update
sudo apt install -y nodejs npm
再通过npm全局安装Swagger UI和Swagger Editor:
sudo npm install -g swagger-ui-express swagger-editor-cli
若未使用Node.js,也可通过系统包管理器安装(如sudo apt install swagger-jsdoc swagger-ui-express),但Node.js方式更灵活。
2. 编写OpenAPI规范文件
Swagger文档基于OpenAPI Specification(OAS),常用格式为swagger.yaml或swagger.json。以下是一个简单的swagger.yaml示例:
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
description: A sample API for demonstration
servers:
- url: http://localhost:3000
description: Local development server
paths:
/users:
get:
summary: List all users
description: Retrieve a list of all users in the system
responses:
'200':
description: An array of user objects
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
description: The unique identifier of the user
name:
type: string
description: The full name of the user
required:
- id
- name
该文件定义了API的基本信息(标题、版本)、服务器地址、/users端点的GET操作及返回的用户模型。
3. 集成Swagger到应用(以Express为例)
若项目使用Express框架,可通过swagger-ui-express中间件快速集成Swagger UI。首先安装依赖:
sudo npm install --save express swagger-ui-express
然后在Express应用中配置Swagger:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.yaml'); // 引入规范文件
const app = express();
const PORT = process.env.PORT || 3000;
// 集成Swagger UI,访问/api-docs查看文档
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 示例路由(需与swagger.yaml中的路径一致)
app.get('/users', (req, res) => {
res.json([
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
]);
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});
运行应用后,访问http://localhost:3000/api-docs即可看到Swagger UI界面,包含API文档和测试功能。
4. 可选:使用Swagger Editor编辑规范
若需更便捷地编辑Swagger规范,可使用Swagger Editor。通过npm全局安装:
sudo npm install -g swagger-editor
启动Editor后,访问http://localhost:9000,即可在线编辑swagger.yaml或swagger.json文件,并实时预览文档效果。
5. 可选:Docker部署Swagger
若需要环境一致性,可使用Docker部署Swagger。首先编写Dockerfile:
FROM node:16
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
然后构建并运行容器:
docker build -t swagger-ui .
docker run -d -p 3000:3000 --name swagger-container swagger-ui
访问http://localhost:3000/api-docs即可查看Swagger UI。
以上就是关于“Ubuntu Swagger如何配置API文档”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm