在Ubuntu上搭建Swagger API,通常指的是使用Swagger UI來展示和測試你的API。Swagger UI是一個可視化的工具,它允許用戶查看RESTful API的文檔,并且可以直接在瀏覽器中進行交互式測試。以下是搭建Swagger UI的基本步驟:
安裝Node.js和npm: Swagger UI可以通過Node.js來運行。首先,你需要安裝Node.js和npm(Node.js的包管理器)。
sudo apt update
sudo apt install nodejs npm
你可以通過運行以下命令來檢查Node.js和npm是否安裝成功:
node -v
npm -v
安裝Swagger UI Express: Swagger UI Express是一個可以在Express應用中集成Swagger UI的庫。
npm install swagger-ui-express
創建一個簡單的Express應用:
創建一個新的目錄來存放你的項目,并在該目錄中創建一個名為app.js的文件。
mkdir swagger-demo
cd swagger-demo
touch app.js
使用文本編輯器打開app.js,并添加以下代碼來創建一個基本的Express服務器:
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文檔:
在項目目錄中創建一個名為swagger.yaml的文件,并添加你的API的Swagger規范。這是一個簡單的例子:
swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger UI on Ubuntu
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
required:
- id
- name
運行你的應用: 在終端中運行以下命令來啟動你的Express服務器:
node app.js
現在,你可以在瀏覽器中訪問http://localhost:3000/api-docs來查看Swagger UI界面,并與你的API進行交互。
請注意,這只是一個基本的示例。在實際應用中,你可能需要添加更多的配置和安全措施。此外,Swagger UI也可以直接從Swagger Hub下載靜態文件來部署,但這通常適用于不需要動態生成API文檔的場景。