ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

HoRain云--Swagger UI 与文档发布教程

HoRain云--Swagger UI 与文档发布教程 Swagger UI 是一种基于 OpenAPI 规范原 Swagger 规范的 API 文档可视化工具它能将 API 规范文档转换为交互式 API 文档界面。通过 Swagger UI开发者和用户可以:查看 API 的详细信息直接在界面上测试 API 请求查看请求和响应示例了解不同 API 端点的功能和参数Swagger UI 的优势可视化提供清晰、直观的 API 文档界面交互性支持在线测试 API无需额外工具实时更新代码变更后文档自动更新标准化基于 OpenAPI 规范保持一致性跨语言支持适用于各种编程语言和框架集成 Swagger UI1. 在 Spring Boot 项目中集成添加依赖在pom.xml添加以下依赖:实例!-- Springfox Swagger2 --dependencygroupIdio.springfox/groupIdartifactIdspringfox-swagger2/artifactIdversion3.0.0/version/dependency!-- Springfox Swagger UI --dependencygroupIdio.springfox/groupIdartifactIdspringfox-swagger-ui/artifactIdversion3.0.0/version/dependency或者使用 SpringDoc OpenAPI:实例dependencygroupIdorg.springdoc/groupIdartifactIdspringdoc-openapi-ui/artifactIdversion1.6.14/version/dependency配置 Swagger实例import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.service.Contact;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;ConfigurationEnableSwagger2public class SwaggerConfig {Beanpublic 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(API 接口文档).description(API 接口详细描述).version(1.0.0).contact(new Contact(开发团队, https://example.com, teamexample.com)).build();}}对于 SpringDoc OpenAPI:实例import org.springdoc.core.GroupedOpenApi;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import io.swagger.v3.oas.models.OpenAPI;import io.swagger.v3.oas.models.info.Info;import io.swagger.v3.oas.models.info.Contact;Configurationpublic class SwaggerConfig {Beanpublic OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title(API 接口文档).version(1.0.0).description(API 接口详细描述).contact(new Contact().name(开发团队).email(teamexample.com).url(https://example.com)));}Beanpublic GroupedOpenApi publicApi() {return GroupedOpenApi.builder().group(public-apis).pathsToMatch(/api/**).build();}}2. 在 Node.js Express 项目中集成安装依赖npm install swagger-jsdoc swagger-ui-express --save配置 Swagger实例const express require(express);const swaggerJsDoc require(swagger-jsdoc);const swaggerUi require(swagger-ui-express);const app express();// Swagger 配置const swaggerOptions {definition: {openapi: 3.0.0,info: {title: API 接口文档,version: 1.0.0,description: API 接口详细描述,contact: {name: 开发团队,email: teamexample.com,url: https://example.com}},servers: [{url: http://localhost:3000,description: 开发服务器}]},apis: [./routes/*.js] // API 路由文件的路径};const swaggerDocs swaggerJsDoc(swaggerOptions);app.use(/api-docs, swaggerUi.serve, swaggerUi.setup(swaggerDocs));// ... 其他路由和中间件app.listen(3000, () {console.log(服务器运行在 http://localhost:3000);console.log(API 文档可在 http://localhost:3000/api-docs 访问);});3. 在 Python FastAPI 项目中使用FastAPI 默认集成了 Swagger UI:实例from fastapi import FastAPIapp FastAPI(titleAPI 接口文档,descriptionAPI 接口详细描述,version1.0.0,contact{name: 开发团队,email: teamexample.com,url: https://example.com,},)app.get(/)async def root():return {message: Hello World}Swagger UI 默认可在 /docs 路径访问可通过访问 http://localhost:8000/docs 查看文档。详细内容参见FastAPI 交互式 API 文档编写 API 文档1. Spring Boot 项目中的 API 文档注解实例import io.swagger.annotations.*;import org.springframework.web.bind.annotation.*;RestControllerRequestMapping(/api/users)Api(tags 用户管理)public class UserController {ApiOperation(value 获取用户列表, notes 分页获取所有用户信息)ApiResponses({ApiResponse(code 200, message 成功),ApiResponse(code 400, message 请求参数错误),ApiResponse(code 500, message 服务器内部错误)})GetMapping(/)public PageUser getUsers(ApiParam(value 页码, required true) RequestParam int page,ApiParam(value 每页记录数, required true) RequestParam int size) {// 业务逻辑return userService.getUsers(page, size);}ApiOperation(value 获取单个用户, notes 根据ID获取用户信息)GetMapping(/{id})public User getUser(ApiParam(value 用户ID, required true) PathVariable Long id) {// 业务逻辑return userService.getUser(id);}ApiOperation(value 创建用户, notes 创建新用户)PostMapping(/)public User createUser(ApiParam(value 用户信息, required true) RequestBody UserDTO userDTO) {// 业务逻辑return userService.createUser(userDTO);}}对于 SpringDoc OpenAPI:实例import io.swagger.v3.oas.annotations.*;import io.swagger.v3.oas.annotations.media.*;import io.swagger.v3.oas.annotations.responses.*;import io.swagger.v3.oas.annotations.tags.Tag;import org.springframework.web.bind.annotation.*;RestControllerRequestMapping(/api/users)Tag(name 用户管理, description 用户相关的API)public class UserController {Operation(summary 获取用户列表,description 分页获取所有用户信息)ApiResponses(value {ApiResponse(responseCode 200, description 成功),ApiResponse(responseCode 400, description 请求参数错误),ApiResponse(responseCode 500, description 服务器内部错误)})GetMapping(/)public PageUser getUsers(Parameter(description 页码, required true) RequestParam int page,Parameter(description 每页记录数, required true) RequestParam int size) {// 业务逻辑return userService.getUsers(page, size);}}2. Node.js Express 项目中的 API 文档注释实例/*** swagger* /api/users:* get:* summary: 获取用户列表* description: 分页获取所有用户信息* tags: [用户管理]* parameters:* - in: query* name: page* schema:* type: integer* required: true* description: 页码* - in: query* name: size* schema:* type: integer* required: true* description: 每页记录数* responses:* 200:* description: 成功* content:* application/json:* schema:* type: object* properties:* data:* type: array* items:* $ref: #/components/schemas/User* total:* type: integer* 400:* description: 请求参数错误* 500:* description: 服务器内部错误*/router.get(/users, (req, res) {// 业务逻辑});/*** swagger* components:* schemas:* User:* type: object* required:* - name* - email* properties:* id:* type: integer* description: 用户ID* name:* type: string* description: 用户名* email:* type: string* format: email* description: 用户邮箱*/3. Python FastAPI 项目中的 API 文档实例from fastapi import FastAPI, Query, Pathfrom pydantic import BaseModelfrom typing import List, Optionalapp FastAPI(title用户管理API)class User(BaseModel):id: intname: stremail: strclass Config:schema_extra {example: {id: 1,name: 张三,email: zhangsanexample.com}}app.get(/api/users/,summary获取用户列表,description分页获取所有用户信息,response_modelList[User],tags[用户管理])async def get_users(page: int Query(..., description页码, ge1),size: int Query(..., description每页记录数, ge1, le100)):# 业务逻辑return [{id: 1, name: 张三, email: zhangsanexample.com},{id: 2, name: 李四, email: lisiexample.com}]app.get(/api/users/{user_id},summary获取单个用户,description根据ID获取用户信息,response_modelUser,tags[用户管理])async def get_user(user_id: int Path(..., description用户ID, ge1)):# 业务逻辑return {id: user_id, name: 张三, email: zhangsanexample.com}自定义 Swagger UI1. Spring Boot 自定义配置实例Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(com.example.controller)).paths(PathSelectors.regex(/api/.*)).build().apiInfo(apiInfo()).useDefaultResponseMessages(false) // 禁用默认响应消息.globalResponseMessage(RequestMethod.GET, globalResponses()) // 自定义全局响应消息.securitySchemes(Arrays.asList(apiKey())) // 配置安全认证.securityContexts(Arrays.asList(securityContext())); // 配置安全上下文}private ListResponseMessage globalResponses() {return Arrays.asList(new ResponseMessageBuilder().code(200).message(成功).build(),new ResponseMessageBuilder().code(400).message(请求参数错误).build(),new ResponseMessageBuilder().code(401).message(未授权).build(),new ResponseMessageBuilder().code(403).message(禁止访问).build(),new ResponseMessageBuilder().code(500).message(服务器内部错误).build());}private ApiKey apiKey() {return new ApiKey(JWT, Authorization, header);}private SecurityContext securityContext() {return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex(/api/.*)).build();}private ListSecurityReference defaultAuth() {AuthorizationScope authorizationScope new AuthorizationScope(global, accessEverything);AuthorizationScope[] authorizationScopes new AuthorizationScope[1];authorizationScopes[0] authorizationScope;return Arrays.asList(new SecurityReference(JWT, authorizationScopes));}2. Express 自定义配置实例const options {customCss: .swagger-ui .topbar { display: none }, // 自定义CSScustomSiteTitle: API 文档中心, // 页面标题customfavIcon: /favicon.png, // 自定义图标swaggerOptions: {persistAuthorization: true, // 保留授权信息docExpansion: none, // 默认折叠所有接口tagsSorter: alpha, // 标签按字母排序operationsSorter: alpha, // 操作按字母排序defaultModelsExpandDepth: -1, // 隐藏模型filter: true, // 启用过滤}};app.use(/api-docs, swaggerUi.serve, swaggerUi.setup(swaggerDocs, options));3. FastAPI 自定义配置实例from fastapi import FastAPIfrom fastapi.openapi.docs import get_swagger_ui_htmlfrom fastapi.staticfiles import StaticFilesapp FastAPI(titleAPI 接口文档,docs_urlNone, # 禁用默认的 Swagger UI)app.mount(/static, StaticFiles(directorystatic), namestatic)app.get(/docs, include_in_schemaFalse)async def custom_swagger_ui_html():return get_swagger_ui_html(openapi_urlapp.openapi_url,titleapp.title - API 文档,oauth2_redirect_urlapp.swagger_ui_oauth2_redirect_url,swagger_js_url/static/swagger-ui-bundle.js,swagger_css_url/static/swagger-ui.css,swagger_favicon_url/static/favicon.png,swagger_ui_parameters{docExpansion: none,defaultModelsExpandDepth: -1,filter: True,})文档发布1. 内部发布对于团队内部使用可以直接通过应用程序内部的 Swagger UI 访问:Spring Boot:http://your-app-host:port/swagger-ui/index.htmlExpress:http://your-app-host:port/api-docsFastAPI:http://your-app-host:port/docs2. 静态文档生成使用 Swagger Codegen 生成静态文档# 安装 Swagger Codegen CLI wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.35/swagger-codegen-cli-3.0.35.jar -O swagger-codegen-cli.jar # 生成静态 HTML 文档 java -jar swagger-codegen-cli.jar generate -i http://your-app-host:port/v3/api-docs -l html2 -o ./api-docs使用 Redoc 生成静态文档# 安装 redoc-cli npm install -g redoc-cli # 生成静态 HTML 文档 redoc-cli bundle http://your-app-host:port/v3/api-docs -o ./api-docs/index.html3. 整合到 CI/CD 流程在 CI/CD 管道中添加文档生成和发布步骤:Jenkins 流水线示例实例pipeline {agent anystages {// ... 其他构建和测试阶段stage(Generate API Documentation) {steps {sh java -jar swagger-codegen-cli.jar generate -i http://your-app-host:port/v3/api-docs -l html2 -o ./api-docs}}stage(Publish Documentation) {steps {// 发布到 Nginx 静态文件服务器sh rsync -avz --delete ./api-docs/ userdoc-server:/var/www/api-docs/// 或发布到对象存储(如 AWS S3)sh aws s3 sync ./api-docs/ s3://your-bucket/api-docs/ --delete}}}}GitHub Actions 工作流示例实例name: Generate and Deploy API Docson:push:branches: [ main ]jobs:build-and-deploy:runs-on: ubuntu-lateststeps:- uses: actions/checkoutv2- name: Set up JDKuses: actions/setup-javav2with:distribution: adoptjava-version: 11- name: Build applicationrun: ./mvnw clean package- name: Start applicationrun: |java -jar target/your-app.jar sleep 30 # 等待应用启动- name: Generate API Documentationrun: |wget -q https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.35/swagger-codegen-cli-3.0.35.jar -O swagger-codegen-cli.jarjava -jar swagger-codegen-cli.jar generate -i http://localhost:8080/v3/api-docs -l html2 -o ./api-docs- name: Deploy to GitHub Pagesuses: JamesIves/github-pages-deploy-action4.1.5with:branch: gh-pagesfolder: api-docs4. 使用 API 文档管理平台除了自行部署还可以使用专业的 API 文档管理平台:Swagger Hub: 提供 API 设计和文档托管服务Postman: 不仅可以测试 API还可以发布 API 文档ReadMe.io: 提供全面的 API 文档管理和开发者门户Stoplight: 提供 API 设计、文档和治理工具5. Docker 部署 Swagger UI实例FROM swaggerapi/swagger-ui:latest# 设置环境变量ENV SWAGGER_JSON/swagger/openapi.jsonENV BASE_URL/api-docs# 复制 OpenAPI 规范文件COPY openapi.json /swagger/# 暴露端口EXPOSE 8080# 启动 Swagger UICMD [sh, /usr/share/nginx/docker-run.sh]构建和运行:docker build -t my-swagger-ui . docker run -p 8080:8080 my-swagger-ui访问: http://localhost:8080/api-docs最佳实践1. 文档规范保持简洁明了: 描述应简洁而有针对性分组管理: 使用标签对 API 进行逻辑分组提供示例: 为请求和响应提供示例标准化错误处理: 统一错误响应格式和状态码版本控制: 在文档中明确 API 版本信息2. 安全配置敏感信息处理: 不在文档中暴露敏感信息生产环境配置: 在生产环境中可选择性禁用或限制文档访问认证机制: 配置文档访问认证实例// Spring Boot 配置生产环境禁用 SwaggerBeanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).enable(!environment.acceptsProfiles(Profiles.of(prod)))// ... 其他配置}3. 自动化测试结合文档和测试确保文档内容与实际 API 行为保持一致:实例// Spring Boot 使用 REST Assured 和 Swagger 进行测试Testpublic void validateSwaggerDocumentation() {// 获取 Swagger JSONString swaggerJson given().when().get(/v3/api-docs).then().statusCode(200).extract().asString();// 验证 Swagger 文档OpenAPI openAPI new OpenAPIParser().readContents(swaggerJson, null, null).getOpenAPI();assertNotNull(openAPI);// 验证特定端点是否在文档中assertNotNull(openAPI.getPaths().get(/api/users));}常见问题解决1. Swagger UI 不显示或加载错误检查依赖版本: 确保依赖版本兼容检查配置类: 确保配置类正确注册检查路径映射: 确保路径映射正确检查跨域设置: 如果跨域访问确保 CORS 配置正确2. 接口信息不完整检查注解: 确保所有必要注解都已添加检查包扫描路径: 确保扫描路径包含所有控制器检查模型类: 确保模型类有正确的描述3. 生产环境安全问题配置生产环境禁用或保护文档:# application-prod.properties springdoc.swagger-ui.enabledfalse springdoc.api-docs.enabledfalse或使用基本认证保护:实例ConfigurationProfile(prod)public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.requestMatchers().antMatchers(/swagger-ui/**, /v3/api-docs/**).and().authorizeRequests().anyRequest().hasRole(ADMIN).and().httpBasic();}}总结Swagger UI 是一个强大的 API 文档工具通过正确配置和使用可以大大提高 API 的可用性和开发效率。本教程介绍了 Swagger UI 的基本概念、集成方法、文档编写、自定义配置、文档发布以及最佳实践希望对您的 API 文档工作有所帮助。记住以下关键点:选择适合项目技术栈的 Swagger 集成方式精心设计和编写 API 文档注解或注释根据需要自定义 Swagger UI 界面选择合适的文档发布方式遵循最佳实践确保文档的准确性和安全性通过合理使用 Swagger UI您可以为您的 API 提供专业、交互式的文档让您的 API 更易于理解和使用。
返回列表