在Ubuntu上配置Swagger可以分为几个步骤,具体如下:
首先,确保你的系统上已经安装了Node.js和HTTP Server。如果还没有安装Node.js,可以参考Node.js的官方安装教程进行安装。
# 新建swagger目录
mkdir /opt/swagger
# 进入该目录
cd /opt/swagger
# 下载swagger-editor最新版本
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz
# 解压
tar -xvf v3.16.1.tar.gz
# 删除压缩文件
rm v3.16.1.tar.gz
# 安装 Node.js 和 HttpServer
npm install -g http-server
安装完成后,在swagger目录中执行以下命令启动服务:
http-server -p 8081
然后访问 http://127.0.0.1:8081
来确认是否可以访问 Swagger Editor。
回到swagger目录,下载并解压Swagger UI的最新版本:
cd /opt/swagger
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.48.0.tar.gz
tar -xvf v3.48.0.tar.gz
rm v3.48.0.tar.gz
初始化Node.js项目并安装Express:
npm init -y
npm install express --save
在项目根目录下创建一个名为 index.js
的文件,并添加以下内容:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname)));
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
然后启动HTTP Server:
node index.js
访问 http://127.0.0.1:3000
来确认是否可以访问 Swagger UI。
如果你使用的是Spring Boot项目,可以使用springfox-swagger2
和springfox-swagger-ui
来集成Swagger。
在项目的pom.xml
文件中添加以下依赖:
<dependencies>
<!-- Swagger 2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>YOUR_DESIRED_VERSION</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>YOUR_DESIRED_VERSION</version>
</dependency>
<!-- 其他依赖 -->
</dependencies>
替换YOUR_DESIRED_VERSION
为实际使用的版本号。
创建一个配置类来启用Swagger并定义一些基本信息:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.any())
.paths(PathSelectors.any())
.build();
}
}
这个配置类启用了Swagger,并告诉Swagger扫描所有的API接口来生成文档。
启动Spring Boot项目后,访问 http://localhost:8080/swagger-ui.html
(假设服务端口为8080),可以看到Swagger UI界面,其中展示了项目中定义的所有API接口及其详细信息。
通过以上步骤,你就可以在Ubuntu上成功配置Swagger。根据你的项目类型(Spring Boot或其他),选择相应的配置方法即可。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Swagger在Debian上如何配置