Ubuntu上Swagger API测试实操指南
一 准备环境
二 方式一 使用Docker快速起Swagger UI
docker run -d --name swagger-ui \
-p 38081:8080 \
-e SWAGGER_JSON=/spec/swagger.yaml \
-v /path/to:/spec \
swaggerapi/swagger-ui:v4.15.5
三 方式二 在Node应用中集成Swagger UI
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
servers:
- url: http://localhost:3000
paths:
/users:
get:
summary: List all users
responses:
'200':
description: OK
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
const swaggerDocument = YAML.load('./swagger.yaml');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.get('/users', (req, res) => res.json([{ id: 1, name: 'Alice' }]));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server on ${PORT}, /api-docs`));
四 方式三 使用Swagger Editor编辑与验证
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz
tar -xvf v3.16.1.tar.gz
cd swagger-editor-3.16.1
npm install
npx http-server -p 8080
五 常见问题与自动化测试
const request = require('supertest');
const app = require('./index'); // 上面的 Express 实例
const { expect } = require('chai');
describe('GET /users', () => {
it('should return 200 and an array', async () => {
const res = await request(app).get('/users');
expect(res.status).to.equal(200);
expect(res.body).to.be.an('array');
});
});