在Linux系统上集成Swagger主要分为以下几个步骤:
Swagger是一个基于Java的API文档生成工具,因此你需要一个Java开发环境。你可以使用OpenJDK或Oracle JDK来安装Java。
sudo apt update
sudo apt install openjdk-11-jdk
如果你使用Maven或Gradle来构建你的项目,确保你已经正确配置了依赖项。
在你的 pom.xml
文件中添加Swagger依赖项:
<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>
在你的 build.gradle
文件中添加Swagger依赖项:
dependencies {
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
}
创建一个Swagger配置类来启用Swagger文档生成。
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文档。
打开浏览器并访问 http://localhost:8080/swagger-ui.html
,你应该能够看到Swagger UI界面,其中列出了你的所有API端点。你可以点击每个端点来查看请求和响应的详细信息。
Swagger Editor是一个Swagger UI的在线编辑器,你可以自己搭建一个,也可以使用官方的。
wget https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.50.0/swagger-editor.min.js
wget https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.50.0/swagger-editor.min.css
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="swagger-editor.css">
</head>
<body>
<div id="swagger-editor"></div>
<script src="swagger-editor.js"></script>
<script>
window.onload = function() {
const editor = SwaggerEditor({
url: "https://petstore.swagger.io/v2/api-docs",
dom_id: '#swagger-editor'
});
};
</script>
</body>
</html>
Apache:
sudo a2ensite default.conf
sudo systemctl restart apache2
Nginx:
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.backup
sudo nano /etc/nginx/sites-available/default
修改 server
块中的 root
和 index
指令:
server {
listen 80 default_server;
listen [::]: 80 default_server;
root /var/www/html;
index index.html index.htm;
server_name _;
location / {
try_files $uri $uri/ =404;
}
}
保存并退出编辑器,然后重启Nginx:
sudo systemctl restart nginx
现在,你应该能够通过浏览器访问 http://your_server_ip/swagger-ui
和 http://your_server_ip/swagger-editor
来查看和使用Swagger UI和Swagger Editor。