在Ubuntu系統中調試Swagger接口,你可以遵循以下步驟:
sudo apt update
sudo apt install nodejs npm
接下來,使用npm全局安裝Swagger UI:
sudo npm install -g swagger-ui-express
app.js的文件,并添加以下代碼:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
// 讀取Swagger文檔
const swaggerDocument = YAML.load('./swagger.yaml');
// 使用swagger-ui-express中間件
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 啟動服務器
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
swagger.yaml的文件,并添加你的API接口定義。例如:swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger UI.
version: '1.0.0'
host: localhost:3000
basePath: /api-docs
schemes:
- http
paths:
/users:
get:
summary: List all users
responses:
200:
description: An array 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
node app.js
http://localhost:3000/api-docs,你應該能看到Swagger UI界面,其中列出了你在swagger.yaml文件中定義的所有API接口。你可以在這里測試和調試你的接口。注意:這里的示例使用了Express框架和YAML格式的Swagger文檔。你也可以使用其他編程語言和文檔格式,例如OpenAPI 3.0和JSON格式。只需相應地調整安裝依賴項和代碼即可。