在开始前,确保Linux系统已安装Docker(用于快速部署Swagger工具)和Node.js/npm(用于本地集成Swagger)。若未安装,可通过以下命令安装:
sudo apt update && sudo apt install -y docker.io && sudo systemctl start docker && sudo systemctl enable dockercurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash,然后nvm install --lts。Swagger Editor是交互式工具,用于编写和预览Swagger规范(YAML/JSON格式)。
docker pull swaggerapi/swagger-editor:v4.6.0docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.6.0http://localhost:38080,进入Swagger Editor界面。此处可手动编写API文档,或通过“File”→“Import File”导入现有swagger.yaml/swagger.json文件。Swagger UI是可视化测试工具,用于发送请求并查看响应结果。
docker pull swaggerapi/swagger-ui:v4.15.5docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5http://localhost:38081,点击“Configure”→“Select File”,上传swagger.yaml/swagger.json文件。导入后,界面会自动生成API接口列表。Swagger规范(swagger.yaml或swagger.json)是API的“蓝图”,定义了路径、方法、参数、响应等。示例如下:
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/api/items:
get:
summary: Get a list of items
responses:
'200':
description: A JSON array of items
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Item'
post:
summary: Create a new item
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Item'
responses:
'201':
description: Item created successfully
components:
schemas:
Item:
type: object
properties:
id:
type: integer
name:
type: string
required:
- id
- name
将上述内容保存为swagger.yaml,导入Swagger Editor/UI即可。
导入规范后,在Swagger UI界面中:
/api/items),点击右侧的“Try it out”按钮。{"id": 1, "name": "Sample Item"})。[{"id": 1, "name": "Sample Item"}])、Status code等信息,直观验证API功能。若需将Swagger集成到本地项目(如Node.js),可通过以下步骤实现:
mkdir swagger-project && cd swagger-project && npm init -ynpm install swagger-jsdoc swagger-ui-expressswagger.json(参考步骤4的示例),并编写server.js:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => console.log('Server running on port 3000'));
node server.js,访问http://localhost:3000/api-docs即可查看Swagger UI。通过以上步骤,即可在Linux系统上使用Swagger完成API文档编写、模拟请求及响应验证,提升开发调试效率。