在Ubuntu上测试Swagger(现称为OpenAPI)主要涉及安装和配置Swagger UI和Swagger Editor,然后通过这些工具进行API文档的生成和测试。以下是详细的步骤和方法:
安装Node.js和npm:
sudo apt update
sudo apt install -y nodejs npm
安装Swagger Editor:
sudo npm install -g swagger-editor
启动Swagger Editor:
swagger-editor
这将在默认浏览器中打开Swagger Editor界面。
安装Swagger UI:
sudo npm install -g swagger-ui-express
创建一个简单的Express应用来托管Swagger UI:
mkdir swagger-ui-example
cd swagger-ui-example
npm init -y
npm install express
创建一个名为 server.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));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
创建一个名为 swagger.yaml
的文件,并添加你的Swagger文档。
启动服务器:
node server.js
在浏览器中访问 http://localhost:3000/api-docs
来查看Swagger UI。
访问Swagger UI:
在浏览器中访问 http://your_server_ip:3000/api-docs
来查看和测试API文档。
使用Swagger Editor:
启动Swagger Editor后,访问 http://localhost:8080
,使用你保存的Swagger YAML文件进行API文档的编辑和查看。
集成Spring Boot项目: 在Spring Boot项目中集成Swagger,使用Springfox库来自动化生成API文档。
添加Springfox依赖:
<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:
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.controller"))
.paths(PathSelectors.any())
.build();
}
}
访问Swagger UI:
启动Spring Boot应用后,在浏览器中访问 http://localhost:8080/swagger-ui/
,然后输入配置文件中指定的Swagger JSON文件地址。
通过以上步骤,你可以在Ubuntu上成功安装和配置Swagger,从而方便地进行API文档的生成和测试。