在Linux系统中集成Swagger UI可以让你更方便地查看和测试API文档。以下是详细的步骤指南:
首先,确保你的系统上已经安装了Node.js和npm。
sudo apt update
sudo apt install nodejs npm
使用npm全局安装Swagger UI。
sudo npm install -g swagger-ui-express
mkdir swagger-ui-example
cd swagger-ui-example
npm init -y
app.js
的文件,并添加以下代码:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// Load Swagger document
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// Serve Swagger docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
swagger.yaml
的文件,并添加你的API文档。以下是一个简单的示例:swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger UI integration
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
format: email
email:
type: string
format: email
required:
- id
- name
在终端中运行以下命令来启动你的Express应用:
node app.js
打开浏览器并访问 http://localhost:3000/api-docs
,你应该能够看到Swagger UI界面,并且可以查看和测试你的API文档。
在你的 pom.xml
中添加以下依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
创建一个配置类来启用Swagger文档生成。以下示例适用于Spring Boot和Spring MVC框架:
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
}
启动你的Spring Boot或Spring MVC应用。Swagger会自动生成API文档,并且你可以在浏览器中访问 http://localhost:8080/swagger-ui.html
(假设你的应用程序运行在端口8080上)来查看和测试API文档。
通过以上步骤,你可以在Linux系统中成功集成Swagger,从而方便地展示、测试和管理你的API。