阅读量:94
在Ubuntu上集成Swagger与其他工具,通常涉及以下几个步骤:
1. 在Ubuntu上集成Swagger UI
-
使用Docker:
- 安装Docker:
sudo apt update sudo apt install docker.io - 拉取Swagger UI Docker镜像:
docker pull swaggerapi/swagger-ui-express - 运行Swagger UI容器:
docker run -p 8080:8080 swaggerapi/swagger-ui-express - 访问Swagger UI:
在浏览器中访问
http://localhost:8080,你应该能看到Swagger UI界面。
- 安装Docker:
-
使用Node.js和Express:
- 安装Node.js和npm:
sudo apt update sudo apt install nodejs npm - 创建一个新的Node.js项目:
mkdir swagger-ui-project cd swagger-ui-project npm init -y - 安装Swagger UI Express:
npm install swagger-ui-express - 创建一个简单的Express应用(
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)); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); - 创建Swagger文档(
swagger.yaml):swagger: '2.0' info: title: Sample API description: A sample API to demonstrate Swagger UI integration 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 - 运行应用:
node app.js - 访问Swagger UI:
在浏览器中访问
http://localhost:3000/api-docs,你应该能看到Swagger UI界面。
- 安装Node.js和npm:
2. 在Ubuntu上集成Swagger与Spring Boot
-
创建Spring Boot项目: 使用Spring Initializr创建一个Spring Boot项目,并添加
Spring Web和Springfox Swagger2依赖。 -
配置Swagger: 创建一个配置类来配置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.basePackage("com.example.swaggerdemo.controller")) .paths(PathSelectors.any()) .build(); } } -
创建一个简单的Controller:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Swagger!"; } } -
运行Spring Boot应用: 在终端中运行以下命令来启动Spring Boot应用:
./mvnw spring-boot:run -
访问Swagger UI: 打开浏览器并访问
http://localhost:8080/swagger-ui.html,你应该能够看到你的API文档和测试界面。
通过以上步骤,你可以在Ubuntu上成功集成Swagger与其他工具,进行API文档化和测试。如果在安装过程中遇到问题,可以参考相关的官方文档或社区论坛寻求帮助。