后端AI生成API文档需四步:一用AST提取接口方法签名;二用结构化提示词强制输出YAML;三用Swagger Editor校验语法;四集成CI/CD自动同步至YApi。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

后端开发人员常因AI生成API文档时字段错乱、状态码缺失、参数类型误判导致联调失败,甚至把测试环境URL写进生产文档——这些问题不是模型能力不足,而是输入结构、上下文切片和校验环节失控。
第一步:只喂AST解析后的代码切片,别扔整个.java文件
直接复制OrderController.java全文件丢给AI,它会混淆通用工具类、日志打印、异常包装器等非接口逻辑,把@Log注解当成权限控制,把catch块里的error message当成400响应描述。【必须用AST工具预过滤,仅保留@Controller类中带@RequestMapping/@PostMapping的方法签名+核心业务代码块】
用JavaParser或Spring Boot官方提供的spring-boot-configuration-processor扫描项目,导出method-signature.json;从中提取含路径、动词、@RequestBody类型、@PathVariable变量名的最小单元;粘贴该单元到AI对话框,而非源码文件本身。
这一步操作起来很简单,直接把文件拖进去就行。
第二步:强制AI输出结构化YAML,禁用自然语言解释
很多翻车源于AI返回大段中文说明,比如“该接口用于创建订单,建议在用户登录后调用”——这种内容无法被Swagger扫描,也不能被CI/CD流水线解析。必须用结构化提示词锁死输出格式。
方法一:用XML标签限定输出域
在Prompt开头加:<output_format>openapi: 3.0.3</output_format>,结尾加:<strict_mode>disable natural language explanation, only output valid YAML</strict_mode>。Claude对这类XML指令响应最稳定。
方法二:用```yaml包裹指令
输入:“请严格按以下格式输出,不要任何额外文字:```yaml\npaths:\n /api/v1/orders:\n post:\n summary: 创建订单\n requestBody:\n required: true\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/CreateOrderRequest'\n responses:\n '201':\n description: 订单创建成功\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/Order'\ncomponents:\n schemas:\n CreateOrderRequest:\n type: object\n properties:\n items:\n type: array\n items:\n type: object\n properties:\n productId:\n type: string\n example: \"P1001\"\n quantity:\n type: integer\n example: 2\n required: [items]\n Order:\n type: object\n properties:\n orderId:\n type: string\n example: \"ORD-20260608-001\"\n status:\n type: string\n example: \"CREATED\"\n required: [orderId, status]```”
方法三:指定字段必填项
在Prompt中明确写:“【responses必须包含200、400、500三个状态码条目;parameters中每个字段必须标注required: true/false;schema中所有string字段必须提供example值】”
第三步:用Swagger Editor做语法校验,再导入本地Swagger UI
① 将AI生成的YAML内容复制进 https://editor.swagger.io 页面,点击“Validate”按钮;
② 若报错“Missing required property: paths”,说明AI漏写了paths根节点,需补全;
③ 若提示“$ref to undefined component”,说明schema引用路径错误,检查components下是否真有对应schema定义;
④ 通过验证后,保存为openapi.yaml,放入Spring Boot项目的src/main/resources目录;
⑤ 启动应用,访问 http://localhost:8080/swagger-ui.html,确认接口路径、参数表格、Try it out按钮全部可交互。
注意:Swagger UI不支持直接加载本地YAML文件,必须通过springdoc-openapi配置自动挂载,否则页面空白。
第四步:对接CI/CD,在Git Push后自动生成并覆盖文档
在Maven的pom.xml中添加springdoc-openapi-maven-plugin插件,绑定generate目标到verify阶段;配置inputFile为${project.basedir}/src/main/resources/openapi.yaml;设置outputFileName为generated-openapi.json。
在GitLab CI脚本中加入:
- mvn clean verify -Dspringdoc.api-docs.path=/v3/api-docs
- curl -X POST "http://yapi-server/api/project/123/interface/import" -F "file=@target/generated-openapi.json" -F "token=abc123"
这一步做完,每次git push后,YApi平台上的接口列表会自动刷新,前端工程师打开页面看到的就是最新字段和示例值。















