在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文档的场景。