在Ubuntu上測試API,通常是通過安裝和配置Swagger(現在通常指的是OpenAPI Generator或Swagger UI)來實現的。以下是詳細的步驟:
sudo apt update
sudo apt install nodejs npm
sudo npm install -g swagger-ui-express
創建一個簡單的Express應用并集成Swagger UI:
mkdir swagger-demo
cd swagger-demo
index.js
文件,并添加以下內容:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// 讀取Swagger文檔
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// 使用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 on port ${PORT} /api-docs`);
});
swagger.yaml
文件,并添加你的API定義: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
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 index.js
http://localhost:3000/api-docs
來查看Swagger UI界面,并與你的API進行交互。sudo apt update
sudo apt install docker.io
docker pull swaggerapi/swagger-ui:v4.15.5
docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5
http://localhost:38081/swagger-ui.html
,查看和測試你的API接口。通過以上步驟,你可以在Ubuntu系統中成功安裝并使用Swagger工具來測試API。選擇適合你的方法進行操作即可。