
OpenAPI 3.1 规范生成实战从设计优先到代码优先、验证与 SDK 生成的完整工作流【免费下载链接】agentsMulti-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity项目地址: https://gitcode.com/GitHub_Trending/agents24/agents本指南以 GitHub 推荐项目精选 agents24/agents 仓库中的documentation-generation插件所携带的openapi-spec-generation技能为核心系统讲解 OpenAPI 3.1 规范的创建、维护与验证全流程从手工编写设计优先规范、到基于 FastAPI / tsoa 的代码优先生成再到用 Spectral 与 Redocly 做契约校验最后通过 openapi-generator-cli 产出多语言 SDK。读完本文你将掌握一套可直接落地到 RESTful API 项目中的规范工程化方法并了解该技能在 agents24/agents 这一多 Agent 插件生态中的定位与调用方式。技能定位与使用场景在 agents24/agents 仓库中openapi-spec-generation是一个以 Markdown 形式组织的技能包Skill存放于 plugins/documentation-generation/skills/openapi-spec-generation/与其同属documentation-generation插件的还有 api-documenter.mdAPI 文档专家 Agent、docs-architect.md文档架构师 Agent以及 doc-generate.md文档生成命令。技能包采用渐进式披露progressive disclosure设计SKILL.md 只保留核心概念与最佳实践具体模板与完整示例存放在references/子目录只有按需读取才会加载进上下文从而控制 Token 开销。根据 SKILL.md 的 frontmatter 声明该技能的适用场景包括从零创建 API 文档Creating API documentation from scratch从已有代码生成 OpenAPI 规范Generating OpenAPI specs from existing code设计 API 契约即设计优先Design-first方式校验 API 实现是否与规范一致Validating API implementations against specs从规范生成客户端 SDKGenerating client SDKs from specs搭建 API 文档门户Setting up API documentation portals在仓库整体架构中技能包是插件市场的基础单元之一README 统计全仓库共 183 个技能可通过gh skill install或npx skills add单独安装也可以随插件整体安装详见 docs/harnesses.md 与 README.md。安装后Agent尤其是 api-documenter在接到为 REST API 编写 OpenAPI 3.1 规范这类请求时便会激活该技能并按其模式产出规范。OpenAPI 3.1 的核心结构SKILL.md 首先给出 OpenAPI 3.1 文档的最小骨架顶层必须包含openapi版本声明、info元信息以及可选的servers、paths和components。openapi: 3.1.0 info: title: API Title version: 1.0.0 servers: - url: https://api.example.com/v1 paths: /resources: get: ... components: schemas: ... securitySchemes: ...与 3.0 相比3.1 版本最显著的变化是全面对齐 JSON Schema 2020-12schema 关键字如nullable与type的组合方式、examples替换example等行为更一致。因此 3.1 下建议直接使用标准 JSON Schema 语义来描述数据类型这也是本技能所有模板默认采用openapi: 3.1.0的原因。三种设计方法的选择SKILL.md 用一张对比表明确了规范的生产方式这是决定整个工作流的第一步ApproachDescriptionBest ForDesign-FirstWrite spec before codeNew APIs, contractsCode-FirstGenerate spec from codeExisting APIsHybridAnnotate code, generate specEvolving APIs设计优先Design-First先写 YAML 契约再按契约实现代码。适合新 API 或需要对外承诺稳定契约的场景也适合契约即文档的团队协作模式。代码优先Code-First从既有代码自动导出规范适合存量系统快速补齐文档。代价是规范质量受代码注释与类型声明质量制约。混合Hybrid在代码中通过注解/装饰器驱动生成同时允许手工补充规范片段适合持续演进的 API。本技能的references/目录恰好为这三种路线各提供了一套可复用的模板details.md中的完整手写规范设计优先、code-first-and-tooling.md中的 FastAPI 与 tsoa 代码代码优先/混合以及 Spectral/Redocly 校验服务于设计优先与混合的持续保障。模板一完整 API 规范设计优先完整模板与演练示例存放在 references/details.mdSKILL.md 明确提示当你需要具体模板时读取该文件。下面是一份可直接复用的用户管理 API完整规范覆盖了info元信息、多环境servers、tags分组、完整 CRUD 路径、$ref复用、错误响应、认证方案与示例数据openapi: 3.1.0 info: title: User Management API description: | API for managing users and their profiles. ## Authentication All endpoints require Bearer token authentication. ## Rate Limiting - 1000 requests per minute for standard tier - 10000 requests per minute for enterprise tier version: 2.0.0 contact: name: API Support email: api-supportexample.com url: https://docs.example.com license: name: MIT url: https://opensource.org/licenses/MIT servers: - url: https://api.example.com/v2 description: Production - url: https://staging-api.example.com/v2 description: Staging - url: http://localhost:3000/v2 description: Local development tags: - name: Users description: User management operations - name: Profiles description: User profile operations - name: Admin description: Administrative operations paths: /users: get: operationId: listUsers summary: List all users description: Returns a paginated list of users with optional filtering. tags: - Users parameters: - $ref: #/components/parameters/PageParam - $ref: #/components/parameters/LimitParam - name: status in: query description: Filter by user status schema: $ref: #/components/schemas/UserStatus - name: search in: query description: Search by name or email schema: type: string minLength: 2 maxLength: 100 responses: 200: description: Successful response content: application/json: schema: $ref: #/components/schemas/UserListResponse examples: default: $ref: #/components/examples/UserListExample 400: $ref: #/components/responses/BadRequest 401: $ref: #/components/responses/Unauthorized 429: $ref: #/components/responses/RateLimited security: - bearerAuth: [] post: operationId: createUser summary: Create a new user description: Creates a new user account and sends welcome email. tags: - Users requestBody: required: true content: application/json: schema: $ref: #/components/schemas/CreateUserRequest examples: standard: summary: Standard user value: email: userexample.com name: John Doe role: user admin: summary: Admin user value: email: adminexample.com name: Admin User role: admin responses: 201: description: User created successfully content: application/json: schema: $ref: #/components/schemas/User headers: Location: description: URL of created user schema: type: string format: uri 400: $ref: #/components/responses/BadRequest 409: description: Email already exists content: application/json: schema: $ref: #/components/schemas/Error security: - bearerAuth: [] /users/{userId}: parameters: - $ref: #/components/parameters/UserIdParam get: operationId: getUser summary: Get user by ID tags: - Users responses: 200: description: Successful response content: application/json: schema: $ref: #/components/schemas/User 404: $ref: #/components/responses/NotFound security: - bearerAuth: [] patch: operationId: updateUser summary: Update user tags: - Users requestBody: required: true content: application/json: schema: $ref: #/components/schemas/UpdateUserRequest responses: 200: description: User updated content: application/json: schema: $ref: #/components/schemas/User 400: $ref: #/components/responses/BadRequest 404: $ref: #/components/responses/NotFound security: - bearerAuth: [] delete: operationId: deleteUser summary: Delete user tags: - Users - Admin responses: 204: description: User deleted 404: $ref: #/components/responses/NotFound security: - bearerAuth: [] - apiKey: [] components: schemas: User: type: object required: - id - email - name - status - createdAt properties: id: type: string format: uuid readOnly: true description: Unique user identifier email: type: string format: email description: User email address name: type: string minLength: 1 maxLength: 100 description: User display name status: $ref: #/components/schemas/UserStatus role: type: string enum: [user, moderator, admin] default: user avatar: type: string format: uri nullable: true metadata: type: object additionalProperties: true description: Custom metadata createdAt: type: string format: date-time readOnly: true updatedAt: type: string format: date-time readOnly: true UserStatus: type: string enum: [active, inactive, suspended, pending] description: User account status CreateUserRequest: type: object required: - email - name properties: email: type: string format: email name: type: string minLength: 1 maxLength: 100 role: type: string enum: [user, moderator, admin] default: user metadata: type: object additionalProperties: true UpdateUserRequest: type: object minProperties: 1 properties: name: type: string minLength: 1 maxLength: 100 status: $ref: #/components/schemas/UserStatus role: type: string enum: [user, moderator, admin] metadata: type: object additionalProperties: true UserListResponse: type: object required: - data - pagination properties: data: type: array items: $ref: #/components/schemas/User pagination: $ref: #/components/schemas/Pagination Pagination: type: object required: - page - limit - total - totalPages properties: page: type: integer minimum: 1 limit: type: integer minimum: 1 maximum: 100 total: type: integer minimum: 0 totalPages: type: integer minimum: 0 hasNext: type: boolean hasPrev: type: boolean Error: type: object required: - code - message properties: code: type: string description: Error code for programmatic handling message: type: string description: Human-readable error message details: type: array items: type: object properties: field: type: string message: type: string requestId: type: string description: Request ID for support parameters: UserIdParam: name: userId in: path required: true description: User ID schema: type: string format: uuid PageParam: name: page in: query description: Page number (1-based) schema: type: integer minimum: 1 default: 1 LimitParam: name: limit in: query description: Items per page schema: type: integer minimum: 1 maximum: 100 default: 20 responses: BadRequest: description: Invalid request content: application/json: schema: $ref: #/components/schemas/Error example: code: VALIDATION_ERROR message: Invalid request parameters details: - field: email message: Must be a valid email address Unauthorized: description: Authentication required content: application/json: schema: $ref: #/components/schemas/Error example: code: UNAUTHORIZED message: Authentication required NotFound: description: Resource not found content: application/json: schema: $ref: #/components/schemas/Error example: code: NOT_FOUND message: User not found RateLimited: description: Too many requests content: application/json: schema: $ref: #/components/schemas/Error headers: Retry-After: description: Seconds until rate limit resets schema: type: integer X-RateLimit-Limit: description: Request limit per window schema: type: integer X-RateLimit-Remaining: description: Remaining requests in window schema: type: integer examples: UserListExample: value: data: - id: 550e8400-e29b-41d4-a716-446655440000 email: johnexample.com name: John Doe status: active role: user createdAt: 2024-01-15T10:30:00Z pagination: page: 1 limit: 20 total: 1 totalPages: 1 hasNext: false hasPrev: false securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: JWT token from /auth/login apiKey: type: apiKey in: header name: X-API-Key description: API key for service-to-service calls security: - bearerAuth: []这份模板在结构层面演示了几条关键工程实践$ref复用优先分页参数PageParam/LimitParam、路径参数UserIdParam、通用错误响应BadRequest/Unauthorized/NotFound/RateLimited全部抽到components下路径中只做引用。这保证了单点定义、处处生效是 SKILL.md 中Use $ref最佳实践的直接体现。错误响应的完整建模Errorschema 同时包含机器可读的code、面向用户的message、可选的字段级details数组与requestId并将 400/401/404/429 等状态码统一映射为可复用组件配合限流响应头Retry-After、X-RateLimit-Limit、X-RateLimit-Remaining让消费者无需猜测异常形态。可空与枚举显式化avatar用nullable: true明确表达可空语义status/role用enum约束取值UpdateUserRequest用minProperties: 1防止空更新请求。这些都与 SKILL.mdDont forget nullable的告诫一一对应。示例驱动消费examples组件给出真实 UUID、真实时间戳等贴近生产的值比空洞的 schema 更能帮助 SDK 生成与开发者联调。模板二代码优先生成Python/FastAPI当面对存量代码或希望文档随代码走时代码优先是更经济的选择。references/code-first-and-tooling.md给出了 FastAPI 的完整示例——FastAPI 基于 Pydantic 与类型注解在运行时自动产出 OpenAPI schema天然适配代码优先/混合路线。核心要点如下应用级元信息在FastAPI(...)构造函数中传入title、description、version、openapi_tags与servers这些会直接映射到规范的info、tags与servers字段。枚举即 enum用class UserStatus(str, Enum)与class UserRole(str, Enum)定义状态与角色生成出的 schema 自动带enum约束。Pydantic 模型即 schemaUserBase/UserCreate/UserUpdate/User等模型自动转成components.schemasField(..., min_length1, max_length100)等约束原样落入 JSON SchemaField(..., aliascreatedAt)用于输出 camelCase 的字段名配合model_config {populate_by_name: True}兼顾序列化与反序列化。示例注入通过model_config {json_schema_extra: {examples: [...]}}为请求体提供标准示例等价于手写规范中的examples。端点注解即路径定义app.get(/users, response_modelUserListResponse, tags[Users], summary..., responses{400: {...}})声明返回模型、标签、摘要与错误响应Query(1, ge1)映射 query 参数Path(..., descriptionUser ID)映射路径参数status_code201与status_code204声明创建/删除语义。导出规范通过app.openapi()方法即可把当前应用导成字典if __name__ __main__: import json print(json.dumps(app.openapi(), indent2))这份 FastAPI 模板与手写规范描述的是同一个用户管理 API二者可互相验证——这正是混合路线的价值以代码为单一事实源同时确保生成的规范与设计优先版本保持一致。模板三代码优先生成TypeScript/tsoa对于 TypeScript 技术栈references/code-first-and-tooling.md提供了基于 tsoa 装饰器的等价实现。tsoa 通过类与装饰器在编译期扫描控制器从 TypeScript 类型生成 OpenAPI 规范控制器路由Route(users)声明路径前缀Tags(Users)分组类内Get()/Post()/Patch()/Delete()声明 HTTP 方法与子路径如Get({userId})。参数与请求体Query() page: number 1、Path() userId: string、Body() body: CreateUserRequest分别对应 query、path 与 requestBody。安全与响应Security(bearerAuth)声明认证要求ResponseErrorResponse(400, Invalid request)声明错误响应SuccessResponse(201, Created)声明成功状态码this.setStatus(201)在实现中配合使用。示例与文档ExampleUserListResponse({...})注入响应示例JSDoc 注释param page Page number (1-based)会进入生成的描述字段因此保持注释质量就是保持文档质量。类型即 schemaTSinterface/enum如UserStatus、UserRole、Pagination直接映射为 components.schemascreatedAt: Date自动映射为date-time格式。tsoa 路线适合希望TypeScript 类型系统与 API 契约同构的团队类型定义即 schema 定义装饰器即路径描述两者的偏差在编译期即可暴露。模板四规范校验与 LintingSpectral Redocly无论走哪条路线规范进入 CI 之前都应经过自动校验。references/code-first-and-tooling.md给出了两条互补的工具链# Install validation tools npm install -g stoplight/spectral-cli npm install -g redocly/cliSpectral 自定义规则集.spectral.yamlSpectral 是规则驱动的 linter内置spectral:oasOpenAPI 核心规则与spectral:asyncapi事件驱动规范两套基线可叠加自定义规则# Spectral ruleset (.spectral.yaml) cat .spectral.yaml EOF extends: [spectral:oas, spectral:asyncapi] rules: # Enforce operation IDs operation-operationId: error # Require descriptions operation-description: warn info-description: error # Naming conventions operation-operationId-valid-in-url: true # Security operation-security-defined: error # Response codes operation-success-response: error # Custom rules path-params-snake-case: description: Path parameters should be snake_case severity: warn given: $.paths[*].parameters[?(.in path)].name then: function: pattern functionOptions: match: ^[a-z][a-z0-9_]*$ schema-properties-camelCase: description: Schema properties should be camelCase severity: warn given: $.components.schemas[*].properties[*]~ then: function: casing functionOptions: type: camel EOF # Run Spectral spectral lint openapi.yaml要点说明内置规则开启即用operation-operationId强制每个操作有 operationIdSDK 生成的函数名依赖它、info-description、operation-security-defined、operation-success-response等都是开箱即用的强制项。自定义规则基于 JSONPathgiven字段用 JSONPath 定位目标节点。上例中path-params-snake-case把匹配范围限定在in path的参数用pattern函数约束为蛇形命名schema-properties-camelCase用casing函数约束为 camelCase。这种规则即配置的方式让命名规范SKILL.mdDont mix styles可以被机器强制执行而不是靠评审人肉把关。Redocly 规则集redocly.yamlRedocly 侧重点在于文档渲染与示例完整性校验同样支持自定义规则与 MIME 类型白名单# Redocly config (redocly.yaml) cat redocly.yaml EOF extends: - recommended rules: no-invalid-media-type-examples: error no-invalid-schema-examples: error operation-4xx-response: warn request-mime-type: severity: error allowedValues: - application/json response-mime-type: severity: error allowedValues: - application/json - application/problemjson theme: openapi: generateCodeSamples: languages: - lang: curl - lang: python - lang: javascript EOF # Run Redocly redocly lint openapi.yaml redocly bundle openapi.yaml -o bundled.yaml redocly preview-docs openapi.yaml其中no-invalid-schema-examples会校验示例是否满足 schema 约束如枚举值是否合法request-mime-type/response-mime-type强制请求与响应的内容类型避免出现文档声明 JSON 而实际返回 XML 的契约漂移theme.openapi.generateCodeSamples还能在渲染文档时自动生成 curl/Python/JavaScript 三种语言的调用示例。redocly bundle用于把多文件含$ref外部引用的规范打包为单个文件redocly preview-docs则在本地起一个可交互的文档预览服务。从规范生成多语言 SDK规范一旦通过校验即可作为契约编译源批量产出客户端。references/code-first-and-tooling.md使用 OpenAPI Generator 的官方 CLI# OpenAPI Generator npm install -g openapitools/openapi-generator-cli # Generate TypeScript client openapi-generator-cli generate \ -i openapi.yaml \ -g typescript-fetch \ -o ./generated/typescript-client \ --additional-propertiessupportsES6true,npmNamemyorg/api-client # Generate Python client openapi-generator-cli generate \ -i openapi.yaml \ -g python \ -o ./generated/python-client \ --additional-propertiespackageNameapi_client # Generate Go client openapi-generator-cli generate \ -i openapi.yaml \ -g go \ -o ./generated/go-client-i指定规范文件-g选择生成器typescript-fetch、python、go等-o指定输出目录--additional-properties注入生成器专属配置如 npm 包名、Python 包名。由于 SDK 方法名来自operationId函数签名来自components.schemas因此模板一中强调的 operationId 唯一性与 schema 完整性会直接决定 SDK 的质量。生成后的客户端可接入 CI 与发布流水线形成改规范 → 校验 → 重生成 SDK → 发版的闭环。最佳实践Dos 与 DontsSKILL.md 将经验收敛为一组正反对照的检查清单可与上述模板一一对应验证应该做Dos使用$ref复用schema、参数与响应避免同一类型散落多处见模板一的components.parameters/responses。补充真实示例examples帮助消费者与 SDK 工具理解数据形态。完整记录错误把 400/401/404/409/429 等所有可能状态码全部建模模板一的Errorschema 与BadRequest等组件即是范例。对 API 进行版本化可以放在 URL/v2或请求头中本模板采用 URL 前缀 info.version双重表达。规范变更遵循语义化版本SemVer破坏性变更升主版本新增兼容能力升次版本。不要做Donts不要写泛泛的描述如 Returns datadescription 应具体到行为、约束与边界条件。不要跳过安全定义所有需要认证的端点都应声明security与securitySchemes模板一同时定义了 JWT Bearer 与 API Key 两套方案。不要忘记可空性用nullable: true显式表达可空避免消费者默认所有字段非空。不要混用命名风格路径参数统一 snake_case、schema 属性统一 camelCase并用 Spectral 自定义规则强制。不要硬编码 URL多环境地址放入servers或用 server variables 表达可变部分。技能在仓库生态中的协作方式在 agents24/agents 中该技能并不是孤立存在的。调用链路大致为用户在 Claude Code 等 harness 中通过/plugin install documentation-generation安装插件README 中的标准用法激活 api-documenter.md 这一 AgentAgent 在接到 API 文档/规范生成任务时加载openapi-spec-generation技能技能先提供 SKILL.md 的核心框架再按需读取 references/details.md 与 references/code-first-and-tooling.md 中的完整模板。同时doc-generate.md 命令提供了$ARGUMENTS占位式请求模板与 OpenAPI 3.0 快速模板其doc-generate流程同样强调从代码中抽取端点、参数与响应以及 AST 解析脚本extract_pydantic_schemas来从源码自动抽取 Pydantic 模型——可以作为该技能代码优先路线的补充实现参考。整个插件体系遵循单一事实源plugins/ 渐进式披露的设计保证了规范生成的知识既不缺失、也不臃肿地进入每次对话上下文。总结openapi-spec-generation技能为 RESTful API 的契约工程提供了一条完整的可执行路径设计优先路线可以直接套用 references/details.md 的完整 YAML 模板代码优先路线可参考 references/code-first-and-tooling.md 的 FastAPI 与 tsoa 实现无论哪条路线都应叠加 Spectral Redocly 的自动校验并以 openapi-generator-cli 产出多语言 SDK最后用 SKILL.md 中的 Dos/Donts 清单做一次人工审计。将这套方法接入 CI 后OpenAPI 规范就不再是一份静态文档而是驱动文档、SDK 与实现保持同步的活契约。【免费下载链接】agentsMulti-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity项目地址: https://gitcode.com/GitHub_Trending/agents24/agents创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考