要在Ubuntu上運行Swagger,您需要遵循以下步驟:
安裝Node.js和npm(Node.js包管理器): 如果您還沒有安裝Node.js和npm,請訪問https://nodejs.org/en/download/package-manager/ubuntu/ 下載并安裝適用于Ubuntu的Node.js和npm。
全局安裝Swagger UI Express: 打開終端,然后運行以下命令以全局安裝Swagger UI Express:
npm install -g swagger-ui-express
創建一個簡單的Swagger應用:
在您的開發目錄中創建一個名為app.js
的新文件,并添加以下代碼:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
const port = process.env.PORT || 3000;
// 讀取Swagger文檔
const swaggerDocument = YAML.load('./swagger.yaml');
// 使用swagger-ui-express中間件
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 啟動服務器
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
創建一個Swagger文檔:
在您的開發目錄中創建一個名為swagger.yaml
的新文件,并添加以下示例Swagger文檔:
swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger UI Express
version: '1.0.0'
host: localhost:3000
basePath: /
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
運行Swagger應用:
在終端中,導航到包含app.js
文件的目錄,然后運行以下命令啟動應用:
node app.js
訪問Swagger UI: 打開瀏覽器,訪問http://localhost:3000/api-docs。您應該看到Swagger UI界面,其中顯示了您的API文檔。
現在您已經在Ubuntu上成功運行了Swagger。您可以繼續開發和擴展您的API以及相應的Swagger文檔。