Swagger(現稱OpenAPI Specification)是一套用于設計、構建、文檔化和使用RESTful API的工具集,支持自動生成交互式API文檔。以下是分框架/語言的詳細步驟,涵蓋主流場景:
sudo apt update && sudo apt install openjdk-11-jdk
pom.xml)或Gradle(build.gradle)以管理Swagger依賴。在項目的pom.xml(Maven)或build.gradle(Gradle)中添加以下依賴:
<!-- Springfox Swagger2(核心依賴) -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Springfox Swagger UI(交互式文檔界面) -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Gradle配置類似,將implementation替換為compile即可。
創建一個配置類(如SwaggerConfig.java),用@Configuration和@EnableSwagger2注解啟用Swagger,并通過Docket Bean指定掃描的包路徑:
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.controller")) // 替換為你的Controller包路徑
.paths(PathSelectors.any()) // 掃描所有路徑
.build();
}
}
可選配置:通過apiInfo()方法添加文檔標題、描述、版本等信息,提升可讀性。
在Controller類和方法上添加Swagger注解,明確API的功能、參數、返回值等信息:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
@Api(tags = "用戶管理", description = "用戶相關操作接口") // 類級別注解,描述模塊功能
public class UserController {
@GetMapping("/{id}")
@ApiOperation(value = "獲取用戶信息", notes = "根據用戶ID查詢詳細信息") // 方法級別注解,描述接口功能
public User getUserById(
@PathVariable @ApiParam(value = "用戶ID", required = true, example = "1") Long id) { // 參數注解,描述參數信息
// 業務邏輯
return userService.getUserById(id);
}
@PostMapping
@ApiOperation(value = "創建用戶", notes = "新增用戶信息")
public User createUser(@RequestBody @ApiParam(value = "用戶對象", required = true) User user) {
// 業務邏輯
return userService.createUser(user);
}
}
常用注解說明:
@Api:描述Controller模塊的功能;@ApiOperation:描述接口的具體功能;@ApiParam:描述接口參數的詳細信息(如是否必填、示例值);@ApiResponse:描述接口的返回結果(如狀態碼、響應內容)。啟動Spring Boot應用后,在瀏覽器中訪問以下URL(端口號根據項目配置調整):
http://localhost:8080/swagger-ui.html
進入后,可看到所有掃描到的API接口,點擊接口名稱可查看詳細信息(如參數、返回值、請求示例),并支持TRY IT OUT功能直接測試接口。
npm install --save swagger-ui-express swagger-jsdoc
swagger.js文件定義API規范,然后在app.js中加載:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');
const app = express();
// 定義Swagger選項
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Node.js API文檔',
version: '1.0.0',
description: 'API文檔示例'
}
},
apis: ['./routes/*.js'] // 指定API路由文件路徑
};
const specs = swaggerJsdoc(options);
// 掛載Swagger UI
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
app.listen(3000, () => console.log('Server running on port 3000'));
http://localhost:3000/api-docs即可查看文檔。pip install flask flask-swagger-ui
from flask import Flask, jsonify
from flask_swagger_ui import get_swaggerui_blueprint
app = Flask(__name__)
# Swagger UI配置
SWAGGER_URL = '/api-docs'
API_URL = '/static/swagger.json'
swaggerui_blueprint = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={'app_name': "Flask API Docs"}
)
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
# 示例API
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
"""獲取用戶信息
---
parameters:
- name: user_id
in: path
type: integer
required: true
description: 用戶ID
responses:
200:
description: 用戶信息
schema:
type: object
properties:
id:
type: integer
name:
type: string
"""
return jsonify({'id': user_id, 'name': 'John Doe'})
if __name__ == '__main__':
app.run(debug=True)
http://localhost:5000/api-docs即可查看文檔。securityDefinitions配置(如OAuth2、API Key),限制文檔訪問權限。通過以上步驟,可根據項目框架快速生成并管理API文檔,提升團隊協作效率。