在Debian上自定义Swagger UI,可以按照以下步骤进行:
1. 安装Swagger UI
首先,你需要安装Swagger UI。你可以使用npm来安装Swagger UI:
sudo apt update sudo apt install npm sudo npm install -g swagger-ui-express
2. 创建一个简单的Express应用
创建一个新的目录并进入该目录:
mkdir swagger-ui-customization cd swagger-ui-customization
然后,创建一个app.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中间件 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}`); });
3. 创建Swagger文档
在项目目录中创建一个swagger.yaml
文件,并添加你的API文档:
swagger: '2.0' info: title: Sample API description: A sample API to demonstrate Swagger UI customization version: '1.0.0' 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 name: type: string
4. 自定义Swagger UI
你可以通过修改swagger-ui-express
的配置来自定义Swagger UI。例如,你可以更改主题、添加自定义CSS或JavaScript文件等。
更改主题
你可以使用Swagger UI的预定义主题或自定义主题。以下是如何使用预定义主题的示例:
const customUiConfig = { deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], layout: "StandaloneLayout", requestInterceptor: (request) => { // 自定义请求拦截器 return request; }, responseInterceptor: (response) => { // 自定义响应拦截器 return response; } }; app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, customUiConfig));
添加自定义CSS或JavaScript
你可以在项目中创建一个public
目录,并在其中添加自定义的CSS或JavaScript文件。然后在app.js
中配置Swagger UI以使用这些文件:
const path = require('path'); app.use('/webjars', express.static(path.join(__dirname, 'node_modules', 'swagger-ui-dist'))); app.use('/custom-css', express.static(path.join(__dirname, 'public', 'css'))); app.use('/custom-js', express.static(path.join(__dirname, 'public', 'js'))); const customUiConfig = { deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], layout: "StandaloneLayout", requestInterceptor: (request) => { // 自定义请求拦截器 return request; }, responseInterceptor: (response) => { // 自定义响应拦截器 return response; }, customCssUrl: '/custom-css/custom.css', customJsUrl: '/custom-js/custom.js' }; app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, customUiConfig));
5. 运行应用
最后,运行你的Express应用:
node app.js
现在,你可以访问http://localhost:3000/api-docs
来查看自定义后的Swagger UI。
通过这些步骤,你可以在Debian上自定义Swagger UI,以满足你的需求。