api-spec-validator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Spec Validator
API 规范验证器
This skill validates OpenAPI Specification (OAS) files against a comprehensive set of rules designed to ensure API specifications are AI-agent-friendly and production-ready.
此 skill 根据一套全面的规则验证 OpenAPI Specification (OAS) 文件,旨在确保 API 规范对 AI Agent 友好并达到生产就绪状态。
API Project structure.
API 项目结构。
Every api specification should be organized as an Anypoint API Project with the following structure:
api
├── api.yaml
├── README.md
├── docs/
├── exchange.jsonExchange.json needs to have the following shape:
json
{
"main": "api.yaml",
"name": "<name-of-the-api>",
"organizationId": "8bfc8bbf-5508-419e-aadc-77dfe18a8172",
"groupId": "f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform",
"assetId": "<same-as-the-folder>",
"version": "<any-semver-version default 1.0.0>",
"apiVersion": "v1",
"classifier": "oas",
"dependencies": [],
"originalFormatVersion": "3.0"
}每个 API 规范都应组织为具有以下结构的 Anypoint API Project:
api
├── api.yaml
├── README.md
├── docs/
├── exchange.jsonexchange.json 必须具有以下结构:
json
{
"main": "api.yaml",
"name": "<name-of-the-api>",
"organizationId": "8bfc8bbf-5508-419e-aadc-77dfe18a8172",
"groupId": "f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform",
"assetId": "<same-as-the-folder>",
"version": "<any-semver-version default 1.0.0>",
"apiVersion": "v1",
"classifier": "oas",
"dependencies": [],
"originalFormatVersion": "3.0"
}When to Use This Skill
何时使用此 Skill
Use this skill when:
- Validating or reviewing OpenAPI/OAS/Swagger specifications
- Checking API specs for completeness and best practices
- Ensuring API specs are optimized for AI agent consumption
- Auditing API documentation quality
在以下情况下使用此 skill:
- 验证或审查 OpenAPI/OAS/Swagger 规范
- 检查 API 规范的完整性和最佳实践
- 确保 API 规范针对 AI Agent 的使用进行了优化
- 审核 API 文档质量
Validation Rules
验证规则
Rule 1: OAS Format Required
规则 1:必须使用 OAS 格式
All API specifications must be written in OpenAPI Specification (OAS) format in YAML. Supported versions:
- OAS 3.0.x
- OAS 3.1.x
Translation: All APIs should be written in OAS 3 or bigger and in YAML format.
所有 API 规范都必须使用 YAML 编写,并采用 OpenAPI Specification (OAS) 格式。支持的版本:
- OAS 3.0.x
- OAS 3.1.x
说明:所有 API 都应采用 OAS 3 或更高版本,并以 YAML 格式编写。
Rule 2: API Title Must End with "API"
规则 2:API 标题必须以 API
结尾
APIThe field must end with the word "API" to ensure consistent naming across the portal.
info.titleValid: , ,
Secrets Manager APIObject Store APIAPI Manager APIInvalid: , , ,
TokenizationObjectStoreARM REST servicesExchange - XAPI Serviceinfo.titleAPI有效:、、
Secrets Manager APIObject Store APIAPI Manager API无效:、、、
TokenizationObjectStoreARM REST servicesExchange - XAPI ServiceRule 3: Semantic Versioning Required
规则 3:必须使用语义化版本
The field must use strict Semantic Versioning with three numeric components: .
info.versionMAJOR.MINOR.PATCHValid: , ,
1.0.02.1.30.7.0Invalid: , , , , ,
v1V11.01v1.0.0v2This ensures consistent version formatting across all API specifications, enabling reliable version comparison and tooling support.
info.versionMAJOR.MINOR.PATCH有效:、、
1.0.02.1.30.7.0无效:、、、、、
v1V11.01v1.0.0v2这可确保所有 API 规范使用一致的版本格式,从而支持可靠的版本比较和工具处理。
Rule 4: Operation IDs Required
规则 4:必须提供 Operation ID
Every endpoint operation must have an that is:
operationId- Descriptive and specific: Clearly indicates what the operation does
- Avoids generic names: ❌ ,
get_data,update,post_itemfetch - Follows verb-noun pattern: ✅ ,
calculateTaxRate,provisionCloudServer,getUserPreferencescancelSubscription
Good examples:
- - specific action + specific domain
calculateTaxRate - - clear verb + clear resource
provisionCloudServer - - specific action + specific data
getUserPaymentHistory
Bad examples:
- - too generic
get_data - - missing context
update - - which resource?
create - - fetch what?
fetch
每个端点操作都必须包含一个满足以下条件的 :
operationId- 描述且具体:明确指出该操作执行的内容
- 避免泛化名称:❌ 、
get_data、update、post_itemfetch - 遵循动宾模式:✅ 、
calculateTaxRate、provisionCloudServer、getUserPreferencescancelSubscription
正确示例:
- - 特定操作 + 特定业务域
calculateTaxRate - - 清晰的动词 + 清晰的资源
provisionCloudServer - - 特定操作 + 特定数据
getUserPaymentHistory
错误示例:
- - 过于泛化
get_data - - 缺少上下文
update - - 创建什么资源?
create - - 获取什么?
fetch
Rule 5: Descriptions Required with Context
规则 5:描述必须包含上下文
Every endpoint operation must have a field. Apply special handling for:
description每个端点操作都必须包含 字段。对于以下情况,需要进行特殊处理:
descriptionLegacy Field Mapping
旧版字段映射
If a field name is cryptic or legacy (e.g., , , ), override its description with clear mapping:
v1_status_codelegacy_tierold_categoryyaml
description: "INTERNAL MAPPING: This represents the customer's loyalty tier. Map 'A' to Gold, 'B' to Silver, 'C' to Bronze."如果字段名称含义隐晦或属于旧版(例如 、、),则应使用清晰的映射说明覆盖其 description:
v1_status_codelegacy_tierold_categoryyaml
description: "INTERNAL MAPPING: This represents the customer's loyalty tier. Map 'A' to Gold, 'B' to Silver, 'C' to Bronze."Contextual Warnings
上下文警告
Add "WARNING" notes in descriptions for important operational considerations:
yaml
description: "WARNING: This endpoint is slow. Expect a 5-second delay. Do not retry before 10 seconds."yaml
description: "WARNING: This endpoint is rate-limited to 10 requests per minute per user."在 description 中为重要的操作注意事项添加 注记:
WARNINGyaml
description: "WARNING: This endpoint is slow. Expect a 5-second delay. Do not retry before 10 seconds."yaml
description: "WARNING: This endpoint is rate-limited to 10 requests per minute per user."AI Aliases for Cryptic Paths
隐晦路径的 AI 别名
If the path is cryptic (e.g., , ), use the field to give it a human-readable "AI Alias":
POST /rpc/v2/action_4GET /api/v1/proc/17summaryyaml
summary: "Create Support Ticket"
description: "Creates a new support ticket in the system."如果路径含义隐晦(例如 、),请使用 字段为其提供人类可读的 :
POST /rpc/v2/action_4GET /api/v1/proc/17summaryAI Aliasyaml
summary: "Create Support Ticket"
description: "Creates a new support ticket in the system."Legacy Error Response Handling
旧版错误响应处理
For legacy 400 Bad Request responses, add recovery instructions in the response description to help AI agents parse error bodies and retry correctly:
yaml
responses:
'400':
description: "Bad Request. RECOVERY INSTRUCTIONS: If the response contains 'ERR_04', the date format was wrong. Re-try using YYYY-MM-DD format. If 'ERR_12', the amount exceeded maximum limit - reduce amount to under $10,000."
content:
application/json:
schema:
type: object
properties:
errorCode:
type: string
enum: [ERR_04, ERR_12, ERR_15]
description: "Error code indicating the type of validation failure"
message:
type: string
description: "Human-readable error message"
examples:
dateFormatError:
summary: Date format error
value:
errorCode: "ERR_04"
message: "Invalid date format"Pattern for recovery instructions:
- Start with "RECOVERY INSTRUCTIONS:" in the 400 response description
- Map each error code to specific corrective action
- Be explicit about what to change (format, value range, required fields, etc.)
- Prevent unnecessary retries by being specific about the fix needed
对于旧版 400 Bad Request 响应,请在响应 description 中添加恢复说明,帮助 AI Agent 解析错误正文并正确重试:
yaml
responses:
'400':
description: "Bad Request. RECOVERY INSTRUCTIONS: If the response contains 'ERR_04', the date format was wrong. Re-try using YYYY-MM-DD format. If 'ERR_12', the amount exceeded maximum limit - reduce amount to under $10,000."
content:
application/json:
schema:
type: object
properties:
errorCode:
type: string
enum: [ERR_04, ERR_12, ERR_15]
description: "Error code indicating the type of validation failure"
message:
type: string
description: "Human-readable error message"
examples:
dateFormatError:
summary: Date format error
value:
errorCode: "ERR_04"
message: "Invalid date format"恢复说明模式:
- 在 400 响应 description 中以 开头
RECOVERY INSTRUCTIONS: - 将每个错误代码映射到特定的纠正操作
- 明确说明需要更改的内容(格式、值范围、必填字段等)
- 明确给出所需修复,避免不必要的重试
Rule 6: Examples Required
规则 6:必须提供示例
Every endpoint operation must have at least one example demonstrating:
- Request parameters (if applicable)
- Request body (if applicable)
- Successful response (200/201)
Use the field in request bodies and responses:
examplesyaml
requestBody:
content:
application/json:
examples:
createUser:
summary: Create new user
value:
name: "John Doe"
email: "john@example.com"每个端点操作至少必须包含一个示例,用于展示:
- 请求参数(如适用)
- 请求正文(如适用)
- 成功响应(200/201)
在请求正文和响应中使用 字段:
examplesyaml
requestBody:
content:
application/json:
examples:
createUser:
summary: Create new user
value:
name: "John Doe"
email: "john@example.com"Rule 7: Type Documentation Required
规则 7:必须记录类型
All schema properties must include a field explaining:
description- What the field represents
- Valid values or ranges
- Business logic or constraints
yaml
properties:
status:
type: string
description: "Current order status. Transitions from 'pending' → 'processing' → 'shipped' → 'delivered'."所有 schema 属性都必须包含 字段,用于说明:
description- 该字段表示什么
- 有效值或有效范围
- 业务逻辑或约束条件
yaml
properties:
status:
type: string
description: "Current order status. Transitions from 'pending' → 'processing' → 'shipped' → 'delivered'."Rule 8: Output Types Documentation Required
规则 8:必须记录输出类型
All response schemas must be fully documented with:
- Description for each property
- Data types clearly specified
- Nullable fields explicitly marked
所有响应 schema 都必须完整记录以下内容:
- 每个属性的 description
- 明确指定数据类型
- 明确标记可空字段
Rule 9: No Naked Strings
规则 9:禁止使用裸字符串
If a field has a limited set of options, it must have an defined. Never use plain type for constrained values.
enumstringBad:
yaml
status:
type: string
description: "Order status (pending, shipped, or delivered)"Good:
yaml
status:
type: string
enum: [pending, shipped, delivered]
description: "Current order status"如果字段仅有一组有限的可选值,则必须定义 。绝不能对受约束的值直接使用纯 类型。
enumstring错误:
yaml
status:
type: string
description: "Order status (pending, shipped, or delivered)"正确:
yaml
status:
type: string
enum: [pending, shipped, delivered]
description: "Current order status"Rule 10: Required Fields Explicit
规则 10:必须明确列出必填字段
Always explicitly list required fields in the schema's array to prevent AI agents from "guessing" optional parameters.
requiredyaml
properties:
name:
type: string
email:
type: string
age:
type: integer
required:
- name
- email始终在 schema 的 数组中明确列出必填字段,避免 AI Agent“猜测”哪些参数是可选的。
requiredyaml
properties:
name:
type: string
email:
type: string
age:
type: integer
required:
- name
- emailRule 11: API-Level Identity (info.description)
规则 11:API 级标识(info.description
)
info.descriptionThe field is the first signal an AI agent uses for API-level discovery. When choosing among many APIs, this description determines whether the agent selects the right one.
info.descriptionEvery API must have a non-empty that explains the API's domain, capabilities, and intended use cases.
info.descriptionBad:
yaml
info:
title: Core Services API Reference
version: 1.0.0Good:
yaml
info:
title: Secrets Manager API
version: 1.0.0
description: >
Manages secrets, shared secrets, and TLS contexts for Anypoint Platform.
Provides operations to create, retrieve, update, and delete secrets
including symmetric keys, certificates, and keystores used by Mule
applications and API gateways.info.description每个 API 都必须包含非空的 ,用于说明 API 的业务域、能力和预期用例。
info.description错误:
yaml
info:
title: Core Services API Reference
version: 1.0.0正确:
yaml
info:
title: Secrets Manager API
version: 1.0.0
description: >
Manages secrets, shared secrets, and TLS contexts for Anypoint Platform.
Provides operations to create, retrieve, update, and delete secrets
including symmetric keys, certificates, and keystores used by Mule
applications and API gateways.Fix Instructions
修复说明
When validation finds violations, use the following instructions to fix each rule. Fixes fall into two categories: mechanical (can be scripted) and semantic (require understanding the API's domain).
当验证发现违规项时,请使用以下说明修复每条规则。修复分为两类:机械性修复(可通过脚本完成)和语义性修复(需要理解 API 的业务域)。
Fixing api-title-ends-with-api
(mechanical + semantic)
api-title-ends-with-api修复 api-title-ends-with-api
(机械性 + 语义性)
api-title-ends-with-api- Open the API spec and find the field
info.title - If it already ends with 'API', no change needed
- Otherwise, rename to a clear, descriptive title ending with 'API':
- →
TokenizationTokenization API - →
ObjectStoreObject Store API - →
ARM REST servicesARM REST Services API - →
Exchange - XAPI ServiceExchange Experience API - →
Edge Security PoliciesAnypoint Security Policies API - →
Core Services API ReferenceAccess Management API
- Avoid trailing suffixes like 'Service', 'Reference', 'xAPI', or version numbers before 'API'
- Use title case for the name
- 打开 API 规范并找到 字段
info.title - 如果标题已经以 结尾,则无需更改
API - 否则,将其重命名为清晰且描述性的标题,并以 结尾:
API- →
TokenizationTokenization API - →
ObjectStoreObject Store API - →
ARM REST servicesARM REST Services API - →
Exchange - XAPI ServiceExchange Experience API - →
Edge Security PoliciesAnypoint Security Policies API - →
Core Services API ReferenceAccess Management API
- 避免使用 、
Service、Reference或版本号等尾缀;名称应以xAPI结尾API - 使用 title case 命名
Fixing api-version-semver
(mechanical)
api-version-semver修复 api-version-semver
(机械性)
api-version-semver- Open the API spec and find the field
info.version - Convert the current value to format:
MAJOR.MINOR.PATCH- or
v1orV1→"1"1.0.0 - →
v22.0.0 - or
1.0→"1.0"1.0.0 - →
0.10.1.0 - →
1.231.23.0 - →
v1.01.0.0 - →
v1.0.0(strip the1.0.0prefix)v - →
v2.1.3(strip the2.1.3prefix)v
- Remove any or
vprefix — semver does not use letter prefixesV - Ensure exactly three dot-separated numeric components
- 打开 API 规范并找到 字段
info.version - 将当前值转换为 格式:
MAJOR.MINOR.PATCH- 、
v1或V1→11.0.0 - →
v22.0.0 - 或
1.0→1.01.0.0 - →
0.10.1.0 - →
1.231.23.0 - →
v1.01.0.0 - →
v1.0.0(移除1.0.0前缀)v - →
v2.1.3(移除2.1.3前缀)v
- 移除所有 或
v前缀——semver 不使用字母前缀V - 确保恰好包含三个以点分隔的数字部分
Fixing api-info-description
(semantic)
api-info-description修复 api-info-description
(语义性)
api-info-description- Read the API spec to identify: the , all paths, and the main operations
info.title - Determine the API's domain (e.g., security, deployment, monitoring, API management)
- Write a 2-3 sentence description that answers: What does this API manage? What are its key capabilities? Who or what consumes it?
- Add the field under
descriptionusing YAML block scalar (info) for readability> - Avoid generic descriptions like "This API provides endpoints" — be specific about the domain
- 阅读 API 规范,以识别 、所有路径和主要操作
info.title - 确定 API 的业务域,例如 security、deployment、monitoring 或 API management
- 编写 2 至 3 句话的描述,回答以下问题:该 API 管理什么?其关键能力是什么?哪些人或系统会使用它?
- 使用 YAML 块标量()在
>下添加info字段,以提高可读性description - 避免使用“该 API 提供端点”之类的泛化描述——应具体说明业务域
Fixing operation-id-camel-case
(mechanical + semantic)
operation-id-camel-case修复 operation-id-camel-case
(机械性 + 语义性)
operation-id-camel-case- If is missing: generate one from the HTTP method + path (e.g.,
operationId→GET /users/{id})getUserById - If exists but is snake_case or generic: rename to descriptive camelCase
operationId - Use the pattern: or
verbNoun(e.g.,verbNounQualifier,listEnvironments,createDeployment)getApplicationStatus - The helper script can generate initial IDs;
scripts/add_operation_ids.pycan improve existing onesscripts/improve_operation_ids.py
- 如果缺少 ,则根据 HTTP 方法和路径生成,例如
operationId→GET /users/{id}getUserById - 如果 已存在,但采用 snake_case 或名称过于泛化,则将其重命名为描述性的 camelCase
operationId - 使用 或
verbNoun模式,例如verbNounQualifier、listEnvironments、createDeploymentgetApplicationStatus - 辅助脚本 可以生成初始 ID;
scripts/add_operation_ids.py可以改进现有 IDscripts/improve_operation_ids.py
Fixing operation-description
(semantic)
operation-description修复 operation-description
(语义性)
operation-description- Read the operation's path, method, parameters, and request/response schemas
- Write a description that explains what the operation does, not just restating the path
- Include relevant business context: preconditions, side effects, related operations
- The helper script can add placeholder descriptions that should then be reviewed
scripts/add_descriptions.py
- 阅读操作的路径、方法、参数以及请求和响应 schema
- 编写描述以说明该操作执行的内容,而不只是复述路径
- 包含相关的业务上下文:前置条件、副作用和相关操作
- 辅助脚本 可以添加占位 description,之后仍需进行审查
scripts/add_descriptions.py
Fixing operation-examples
(mechanical + semantic)
operation-examples修复 operation-examples
(机械性 + 语义性)
operation-examples- For each operation missing examples, look at the response schema to understand the shape
- Create a realistic example that covers the main fields
- Add it under the response's (or the appropriate media type)
content.application/json.examples - The helper script can generate examples from schemas
scripts/add_examples.py - The helper script handles DELETE/HEAD operations that may not need response body examples
scripts/fix_delete_head_examples.py
- 对于缺少示例的每个操作,查看响应 schema 以了解其结构
- 创建覆盖主要字段的逼真示例
- 将其添加在响应的 下,或适当的媒体类型下
content.application/json.examples - 辅助脚本 可以根据 schema 生成示例
scripts/add_examples.py - 辅助脚本 用于处理可能不需要响应正文示例的 DELETE/HEAD 操作
scripts/fix_delete_head_examples.py
Fixing input-types-described
(semantic)
input-types-described修复 input-types-described
(语义性)
input-types-described- For each parameter missing a description, examine its name, type, and where it's used
- Write a description that explains what the parameter controls and valid values
- For path parameters: explain what resource it identifies
- For query parameters: explain filtering/pagination behavior and defaults
- 对于缺少 description 的每个参数,检查其名称、类型及使用位置
- 编写 description,说明该参数控制什么内容以及有效值
- 对于路径参数:说明其标识的资源
- 对于查询参数:说明过滤或分页行为以及默认值
Fixing output-response-description
(semantic)
output-response-description修复 output-response-description
(语义性)
output-response-description- For each response missing a description, examine the status code and response schema
- Write a description that explains what the response represents and when it's returned
- For error responses (4xx/5xx): include what triggers the error and how to resolve it
- 对于缺少 description 的每个响应,检查状态码和响应 schema
- 编写 description,说明该响应表示什么以及在何时返回
- 对于错误响应(4xx/5xx):说明触发错误的原因以及解决方法
Fixing request-body-description
(semantic)
request-body-description修复 request-body-description
(语义性)
request-body-description- For each request body missing a description, examine the schema and the operation's purpose
- Write a description that explains what data the caller must provide and any constraints
- 对于缺少 description 的每个请求正文,检查 schema 和操作用途
- 编写 description,说明调用方必须提供哪些数据以及相关约束
Fixing output-types-described
(semantic)
output-types-described修复 output-types-described
(语义性)
output-types-describedSame approach as — ensure every response has a description explaining the returned data.
output-response-description采用与 相同的方法——确保每个响应都有 description,用于说明返回的数据。
output-response-descriptionGeneral Fix Workflow
通用修复工作流
When fixing violations across multiple APIs:
- Run Pass 2 validation on the target API
- Parse the JSON output to identify violations grouped by rule
- Fix violations one rule type at a time (batch similar fixes)
- Re-run Pass 2 to verify fixes — iterate until clean
- Move to the next API
修复多个 API 中的违规项时:
- 对目标 API 执行第 2 轮验证
- 解析 JSON 输出,按规则归类违规项
- 每次修复一种规则类型(批量修复相似问题)
- 重新执行第 2 轮验证以确认修复——持续迭代直至通过
- 移至下一个 API
Validation Process
验证流程
Prerequisites
前置条件
Install the Anypoint CLI tool and API project plugin:
bash
npm install -g anypoint-cli-v4
anypoint-cli-v4 plugins:install anypoint-cli-api-project-plugin安装 Anypoint CLI 工具和 API project 插件:
bash
npm install -g anypoint-cli-v4
anypoint-cli-v4 plugins:install anypoint-cli-api-project-pluginAutomated Validation
自动化验证
Validation should be performed in two passes to ensure both syntax correctness and AI-agent compliance:
验证应分为两轮执行,以确保语法正确性并满足 AI Agent 友好要求:
Pass 1: Basic OAS Format Validation
第 1 轮:基础 OAS 格式验证
First, validate that the OAS file is syntactically correct:
bash
anypoint-cli-v4 api-project validate --json --location=./path/to/folder/with/oasThis validates:
- OpenAPI specification structure and syntax
- Valid YAML/JSON format
- Required OAS fields present
- Basic schema correctness
Important: Only proceed to Pass 2 if Pass 1 succeeds. Fix any syntax errors first.
首先,验证 OAS 文件在语法上是否正确:
bash
anypoint-cli-v4 api-project validate --json --location=./path/to/folder/with/oas此步骤将验证:
- OpenAPI 规范结构和语法
- 有效的 YAML/JSON 格式
- 是否存在 OAS 必填字段
- 基础 schema 正确性
重要:仅当第 1 轮验证成功后才能继续执行第 2 轮。请先修复所有语法错误。
Pass 2: Full Compliance Validation
第 2 轮:完整合规性验证
After Pass 1 succeeds, validate against all AI-agent-friendly rules:
bash
anypoint-cli-v4 api-project validate --json --location=./path/to/folder/with/oas --local-ruleset skills/api-spec-validator/scripts/ruleset.yamlThis validates:
- API title ends with 'API' (Rule 2)
- Semantic versioning in info.version (Rule 3)
- Descriptive operation IDs (Rule 4)
- Comprehensive descriptions with context (Rule 5)
- Examples in requests and responses (Rule 6)
- Type documentation for all properties (Rule 7)
- Output types fully documented (Rule 8)
- No naked strings - enums required (Rule 9)
- Required fields explicitly listed (Rule 10)
- API-level identity - info.description present (Rule 11)
The tool will:
- Parse the OAS file
- Check all validation rules
- Generate a detailed report with violations
- Exit with status code 0 (pass) or 1 (fail)
第 1 轮验证成功后,根据所有 AI Agent 友好规则进行验证:
bash
anypoint-cli-v4 api-project validate --json --location=./path/to/folder/with/oas --local-ruleset skills/api-spec-validator/scripts/ruleset.yaml此步骤将验证:
- API 标题以 结尾(规则 2)
API - 使用 Semantic Versioning(规则 3)
info.version - operation ID 具备描述性(规则 4)
- description 完整且包含上下文(规则 5)
- 请求和响应中包含示例(规则 6)
- 所有属性都有类型文档(规则 7)
- 输出类型文档完整(规则 8)
- 不存在裸字符串——必须使用 enum(规则 9)
- 明确列出必填字段(规则 10)
- 存在 API 级标识——提供 (规则 11)
info.description
该工具将:
- 解析 OAS 文件
- 检查所有验证规则
- 生成包含违规项的详细报告
- 以状态码 0(通过)或 1(失败)退出
Complete Validation Workflow
完整验证工作流
The recommended workflow for validating an API specification:
- Check format: Ensure spec is OAS (not RAML) - convert if needed
- Pass 1 - Basic validation: Run
anypoint-cli-v4 api-project validate --json --location=./path - Fix syntax errors: Address any errors from Pass 1 before continuing
- Pass 2 - Compliance validation: Run with
--local-ruleset skills/api-spec-validator/scripts/ruleset.yaml - Review violations: Check the detailed report for rule violations
- Fix violations: Update spec to address each violation
- Re-run Pass 2: Verify all violations are resolved
验证 API 规范时推荐采用以下工作流:
- 检查格式:确保规范采用 OAS(而非 RAML)——必要时进行转换
- 第 1 轮——基础验证:运行
anypoint-cli-v4 api-project validate --json --location=./path - 修复语法错误:在继续之前解决第 1 轮发现的全部错误
- 第 2 轮——合规性验证:使用 运行
--local-ruleset skills/api-spec-validator/scripts/ruleset.yaml - 审查违规项:检查详细报告中的规则违规情况
- 修复违规项:更新规范以解决每项违规问题
- 重新执行第 2 轮验证:确认所有违规项均已解决
Manual Review Checklist
手动审查清单
When reviewing specs manually:
- Check if spec is in RAML format - if so, translate to OAS first
- Check each endpoint has ,
operationId, and examplesdescription - Verify operation IDs are descriptive (not generic)
- Look for legacy field names requiring mapping explanations
- Identify slow/rate-limited endpoints needing warnings
- Check for cryptic paths needing AI aliases in
summary - Check 400 responses for error codes - add recovery instructions
- Ensure all string fields with limited options use
enum - Verify all schemas have explicit arrays
required - Confirm all properties have meaningful descriptions
手动审查规范时:
- 检查规范是否采用 RAML 格式——如是,先将其转换为 OAS
- 检查每个端点是否都有 、
operationId和示例description - 验证 operation ID 是否具备描述性,而不是泛化名称
- 找出需要映射说明的旧版字段名
- 找出需要添加警告的慢速或受速率限制端点
- 找出需要使用 添加 AI 别名的隐晦路径
summary - 检查 400 响应中的错误代码——添加恢复说明
- 确保所有仅具有有限选项的字符串字段都使用
enum - 验证所有 schema 都明确包含 数组
required - 确认所有属性都有 meaningful description
Running Validation with Claude
使用 Claude 运行验证
Claude will automatically run both validation passes when you ask:
"Validate my API spec at path/to/api-spec.yaml"
"Check this OpenAPI specification for AI-agent compliance"
"Review my OAS file at specs/my-api.yaml"Claude will:
- Run Pass 1 (basic OAS validation)
- If Pass 1 succeeds, run Pass 2 (compliance validation)
- Provide a summary of violations and recommendations
当提出以下要求时,Claude 会自动执行两轮验证:
"Validate my API spec at path/to/api-spec.yaml"
"Check this OpenAPI specification for AI-agent compliance"
"Review my OAS file at specs/my-api.yaml"Claude 将:
- 执行第 1 轮验证(基础 OAS 验证)
- 如果第 1 轮成功,则执行第 2 轮验证(合规性验证)
- 提供违规项摘要和修复建议
Best Practices
最佳实践
Creating AI-Friendly Specs
创建对 AI Agent 友好的规范
When authoring or reviewing specs, optimize for AI agent consumption:
- Use OAS format: Convert RAML specs to OAS for compatibility
- Be explicit: Don't assume the AI knows implicit conventions
- Add context: Explain business rules, state transitions, constraints
- Warn proactively: Surface gotchas (rate limits, slow endpoints, deprecated fields)
- Map legacy fields: Translate internal codes to human-readable meanings
- Document error recovery: Add recovery instructions for 400 responses with error codes
- Use examples liberally: Show don't tell - examples are worth a thousand words
编写或审查规范时,应针对 AI Agent 的使用进行优化:
- 使用 OAS 格式:将 RAML 规范转换为 OAS,以增强兼容性
- 保持明确:不要假设 AI 了解隐含约定
- 添加上下文:解释业务规则、状态转换和约束条件
- 主动发出警告:明确提示潜在问题(速率限制、慢速端点、已弃用字段)
- 映射旧版字段:将内部代码转换为人类可读的含义
- 记录错误恢复方式:为包含错误代码的 400 响应添加恢复说明
- 充分使用示例:以示例代替抽象说明——示例胜过千言万语
Common Issues to Fix
需要修复的常见问题
- Missing API description: Add explaining domain and capabilities
info.description - RAML format: Convert RAML specs to OAS before validation
- Generic operation IDs: Replace with
getDatagetUserProfile - Missing enums: Add enums for status codes, types, categories
- Undocumented fields: Add descriptions explaining purpose and usage
- Missing required arrays: Explicitly list which fields are mandatory
- Cryptic paths: Add summary aliases for or
/rpc/style paths/action/ - Undocumented 400 errors: Add recovery instructions for error codes
- 缺少 API description:添加 ,说明业务域和能力
info.description - RAML 格式:验证前将 RAML 规范转换为 OAS
- 泛化的 operation ID:将 替换为
getDatagetUserProfile - 缺少 enum:为状态代码、类型和类别添加 enum
- 未记录字段:添加 description,说明用途和使用方式
- 缺少 required 数组:明确列出哪些字段为必填字段
- 隐晦路径:为 或
/rpc/风格的路径添加 summary 别名/action/ - 未记录的 400 错误:为错误代码添加恢复说明
Output Format
输出格式
When validating with , the tool provides a structured report:
anypoint-cli-v4Validating API specification...
✓ oas-only: Valid OpenAPI 3.0.2 format
✓ operation-examples: All operations have examples
⚠ Violations found:
1. operation-id-camel-case
- GET /users: operationId 'get_data' must be in camelCase
- Use descriptive names like 'getUserProfile' or 'calculateTaxRate'
2. no-naked-strings
- POST /orders (request): Property 'status' must have enum
- Avoid naked strings with no constraints
3. schema-required-block
- POST /users: Schema must explicitly list required fields
Validation completed with 3 violationsWhen summarizing results for users, organize by rule type and provide actionable fixes.
使用 进行验证时,该工具会提供结构化报告:
anypoint-cli-v4Validating API specification...
✓ oas-only: Valid OpenAPI 3.0.2 format
✓ operation-examples: All operations have examples
⚠ Violations found:
1. operation-id-camel-case
- GET /users: operationId 'get_data' must be in camelCase
- Use descriptive names like 'getUserProfile' or 'calculateTaxRate'
2. no-naked-strings
- POST /orders (request): Property 'status' must have enum
- Avoid naked strings with no constraints
3. schema-required-block
- POST /users: Schema must explicitly list required fields
Validation completed with 3 violations向用户总结结果时,应按规则类型组织,并提供可执行的修复建议。
Related Skills
相关 Skills
- api-schema-inferrer - Infer and generate schemas from examples in OAS specs
- api-doc-generator - Generate markdown documentation with curl examples from OAS specs
- api-schema-inferrer - 根据 OAS 规范中的示例推断并生成 schema
- api-doc-generator - 根据 OAS 规范生成包含 curl 示例的 Markdown 文档
References
参考资料
For detailed examples and guides:
- - Example of a fully compliant spec with all best practices
references/example-good-spec.yaml - - Common mistakes and how to fix them
references/example-violations.yaml
有关详细示例和指南,请参阅:
- - 包含所有最佳实践的完全合规规范示例
references/example-good-spec.yaml - - 常见错误及其修复方式
references/example-violations.yaml