在Ubuntu上编写Swagger API文档的步骤
在Ubuntu系统上,首先需要安装Node.js和npm(Node.js包管理器),这是使用Swagger Editor、Swagger UI等工具的前提。打开终端,执行以下命令:
sudo apt update
sudo apt install -y nodejs npm
安装完成后,可通过nodejs -v和npm -v验证安装是否成功。
Swagger Editor是Swagger生态中的在线/本地编辑工具,支持YAML/JSON格式的OpenAPI规范编写。通过npm全局安装:
sudo npm install -g swagger-editor-cli
安装完成后,启动本地编辑器实例:
swagger-editor-cli start
这会在默认浏览器中打开Swagger Editor(通常为http://localhost:8080),可直接在线编写或导入现有规范文件。
Swagger UI用于将OpenAPI规范转换为交互式网页文档,方便测试接口。若项目基于Node.js,可通过npm安装:
npm install -g swagger-ui-express
后续需结合Express框架集成到项目中(见步骤3)。
OpenAPI规范(OAS)是Swagger文档的基础,定义了API的端点、参数、响应、认证等信息。可通过以下两种方式创建:
打开Swagger Editor后,在左侧编辑区输入YAML格式的规范(示例如下),右侧会实时预览文档效果。完成后点击“Save”保存为swagger.yaml或swagger.json文件。
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
description: A simple API for demonstration
paths:
/users:
get:
summary: Get 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
使用文本编辑器(如vim、nano)直接创建YAML文件,内容参考上述示例。保存至项目目录(如./docs/swagger.yaml)。
若项目是基于Node.js的Web应用(如Express),可将Swagger UI集成到应用中,实现文档与应用的联动。示例如下:
npm install swagger-ui-express yamljs
在Express应用的主文件(如app.js)中添加以下代码:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
// 读取OpenAPI规范文件
const swaggerDocument = YAML.load('./docs/swagger.yaml');
// 集成Swagger UI到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});
node app.js
打开浏览器访问http://localhost:3000/api-docs,即可看到交互式的Swagger文档,支持“Try it out”功能测试接口。
若已有后端代码(如Go、Java、Spring Boot),可使用工具从代码注释或注解自动生成OpenAPI规范,减少手动编写工作量。
go install github.com/swaggo/swag/cmd/swag@latest
docs目录及docs.go文件:swag init
// @Summary Get user by ID
// @Description Retrieve a user by their ID
// @Tags Users
// @Accept json
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func GetUserByID(c *gin.Context) {
// 业务逻辑
}
swag init,docs目录下的swagger.yaml会自动更新。pom.xml中添加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>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot API")
.description("API Documentation")
.version("1.0")
.build();
}
}
@Api(tags = "User Management")
@RestController
@RequestMapping("/users")
public class UserController {
@ApiOperation(value = "Get user by ID", notes = "Returns a single user")
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable int id) {
// 业务逻辑
return ResponseEntity.ok(new User(id, "John Doe"));
}
}
http://localhost:8080/swagger-ui.html即可查看文档。/users、/products),使用tags分类,提高可维护性。info.version中指定API版本(如1.0.0),便于迭代管理。type、required、format(如int64、string),避免歧义。