在Debian上利用Swagger生成API文档的步骤
确保系统已更新并安装基础工具:
sudo apt update && sudo apt upgrade -y
sudo apt install curl git -y
Swagger支持多语言/框架,Debian环境下常见场景及操作如下:
swagger-jsdoc(生成文档)和swagger-ui-express(集成UI):sudo apt install nodejs npm -y
sudo npm install -g swagger-jsdoc swagger-ui-express
swagger.yaml(或swagger.json),定义API规范:openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
description: A demo API for Debian + Swagger
servers:
- url: http://localhost:3000/api
paths:
/users:
get:
summary: List all users
responses:
'200':
description: A list of users
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
sudo apt install openjdk-11-jdk maven -y
java -version # 验证Java安装
mvn -version # 验证Maven安装
pom.xml,加入以下依赖:<dependencies>
<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>
</dependencies>
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.yaml');
const app = express();
// 集成Swagger UI到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 示例路由(需与swagger.yaml中的路径匹配)
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});
app.listen(3000, () => console.log('Server running on port 3000'));
SwaggerConfig.java,启用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.demo.controller")) // 替换为你的Controller包路径
.paths(PathSelectors.any())
.build();
}
}
node app.js
http://localhost:3000/api-docs,即可查看交互式文档。mvn clean install
java -jar target/your-spring-boot-project-0.0.1-SNAPSHOT.jar
http://localhost:8080/swagger-ui.html,查看生成的文档。@ApiOperation、@ApiParam)丰富文档细节(适用于Java/Spring Boot)。例如:@RestController
@RequestMapping("/api")
public class UserController {
@ApiOperation(value = "获取用户信息", notes = "根据ID查询用户详情")
@GetMapping("/user/{id}")
public ResponseEntity<User> getUserById(
@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
// 实现逻辑
}
}
以上步骤覆盖了Debian环境下常见的Swagger文档生成场景,根据实际技术栈选择对应方法即可快速实现API文档的自动化生成与管理。