在Ubuntu上調試Swagger,通常是指安裝Swagger UI和Swagger Editor,并進行相應的配置和測試。以下是詳細的步驟:
sudo apt update
sudo apt install nodejs npm
npm install -g swagger-editor-cli
npm install -g swagger-ui-express
swagger-editor-cli start
默認情況下,Swagger Editor會在瀏覽器中打開。
mkdir swagger-ui-example
cd swagger-ui-example
npm init -y
npm install express
server.js
文件,并添加以下內容:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// Load Swagger document
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// Serve Swagger docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
swagger.yaml
文件,并添加你的API文檔。例如:swagger: '2.0'
info:
title: Sample API
description: This is a sample API documentation for Swagger.
version: 1.0.0
host: localhost:3000
basePath: /api
schemes:
- http
paths:
/users:
get:
summary: Get list of users
description: Returns a list of all users
produces:
- application/json
responses:
'200':
description: A list of users
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
format: int64
username:
type: string
firstName:
type: string
lastName:
type: string
node server.js
這將在瀏覽器中打開Swagger UI界面,地址為 http://localhost:3000/api-docs
。
swagger.yaml
或 swagger.json
),然后可以為每個API接口生成測試用例,也可以直接調用這些接口進行測試。通過以上步驟,你可以在Ubuntu上成功安裝和配置Swagger,并進行API文檔的查看和測試。如果在安裝過程中遇到問題,可以參考相關的官方文檔或社區論壇尋求幫助。