在Ubuntu上集成Swagger与其他工具,通常涉及以下几个步骤:
使用Docker:
sudo apt update
sudo apt install docker.io
docker pull swaggerapi/swagger-ui-express
docker run -p 8080:8080 swaggerapi/swagger-ui-express
http://localhost:8080
,你应该能看到Swagger UI界面。使用Node.js和Express:
sudo apt update
sudo apt install nodejs npm
mkdir swagger-ui-project
cd swagger-ui-project
npm init -y
npm install swagger-ui-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.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
http://localhost:3000/api-docs
,你应该能看到Swagger UI界面。创建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文档化和测试。如果在安装过程中遇到问题,可以参考相关的官方文档或社区论坛寻求帮助。