api-spec-validator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API 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.json
Exchange.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.json
exchange.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
结尾

The
info.title
field must end with the word "API" to ensure consistent naming across the portal.
Valid:
Secrets Manager API
,
Object Store API
,
API Manager API
Invalid:
Tokenization
,
ObjectStore
,
ARM REST services
,
Exchange - XAPI Service
info.title
字段必须以单词
API
结尾,以确保门户中的命名保持一致。
有效:
Secrets Manager API
、
Object Store API
、
API Manager API
无效:
Tokenization
、
ObjectStore
、
ARM REST services
、
Exchange - XAPI Service

Rule 3: Semantic Versioning Required

规则 3:必须使用语义化版本

The
info.version
field must use strict Semantic Versioning with three numeric components:
MAJOR.MINOR.PATCH
.
Valid:
1.0.0
,
2.1.3
,
0.7.0
Invalid:
v1
,
V1
,
1.0
,
1
,
v1.0.0
,
v2
This ensures consistent version formatting across all API specifications, enabling reliable version comparison and tooling support.
info.version
字段必须使用严格的 Semantic Versioning,并包含三个数字部分:
MAJOR.MINOR.PATCH
。
有效:
1.0.0
、
2.1.3
、
0.7.0
无效:
v1
、
V1
、
1.0
、
1
、
v1.0.0
、
v2
这可确保所有 API 规范使用一致的版本格式,从而支持可靠的版本比较和工具处理。

Rule 4: Operation IDs Required

规则 4:必须提供 Operation ID

Every endpoint operation must have an
operationId
that is:
  • Descriptive and specific: Clearly indicates what the operation does
  • Avoids generic names: ❌
    get_data
    ,
    update
    ,
    post_item
    ,
    fetch
  • Follows verb-noun pattern: ✅
    calculateTaxRate
    ,
    provisionCloudServer
    ,
    getUserPreferences
    ,
    cancelSubscription
Good examples:
  • calculateTaxRate
    - specific action + specific domain
  • provisionCloudServer
    - clear verb + clear resource
  • getUserPaymentHistory
    - specific action + specific data
Bad examples:
  • get_data
    - too generic
  • update
    - missing context
  • create
    - which resource?
  • fetch
    - fetch what?
每个端点操作都必须包含一个满足以下条件的
operationId
:
  • 描述且具体:明确指出该操作执行的内容
  • 避免泛化名称:❌
    get_data
    、
    update
    、
    post_item
    、
    fetch
  • 遵循动宾模式:✅
    calculateTaxRate
    、
    provisionCloudServer
    、
    getUserPreferences
    、
    cancelSubscription
正确示例:
  • calculateTaxRate
    - 特定操作 + 特定业务域
  • provisionCloudServer
    - 清晰的动词 + 清晰的资源
  • getUserPaymentHistory
    - 特定操作 + 特定数据
错误示例:
  • get_data
    - 过于泛化
  • update
    - 缺少上下文
  • create
    - 创建什么资源?
  • fetch
    - 获取什么?

Rule 5: Descriptions Required with Context

规则 5:描述必须包含上下文

Every endpoint operation must have a
description
field. Apply special handling for:
每个端点操作都必须包含
description
字段。对于以下情况,需要进行特殊处理:

Legacy Field Mapping

旧版字段映射

If a field name is cryptic or legacy (e.g.,
v1_status_code
,
legacy_tier
,
old_category
), override its description with clear mapping:
yaml
description: "INTERNAL MAPPING: This represents the customer's loyalty tier. Map 'A' to Gold, 'B' to Silver, 'C' to Bronze."
如果字段名称含义隐晦或属于旧版(例如
v1_status_code
、
legacy_tier
、
old_category
),则应使用清晰的映射说明覆盖其 description:
yaml
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 中为重要的操作注意事项添加
WARNING
注记:
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."

AI Aliases for Cryptic Paths

隐晦路径的 AI 别名

If the path is cryptic (e.g.,
POST /rpc/v2/action_4
,
GET /api/v1/proc/17
), use the
summary
field to give it a human-readable "AI Alias":
yaml
summary: "Create Support Ticket"
description: "Creates a new support ticket in the system."
如果路径含义隐晦(例如
POST /rpc/v2/action_4
、
GET /api/v1/proc/17
),请使用
summary
字段为其提供人类可读的
AI Alias
:
yaml
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
examples
field in request bodies and responses:
yaml
requestBody:
  content:
    application/json:
      examples:
        createUser:
          summary: Create new user
          value:
            name: "John Doe"
            email: "john@example.com"
每个端点操作至少必须包含一个示例,用于展示:
  • 请求参数(如适用)
  • 请求正文(如适用)
  • 成功响应(200/201)
在请求正文和响应中使用
examples
字段:
yaml
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
description
field explaining:
  • 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
enum
defined. Never use plain
string
type for constrained values.
Bad:
yaml
status:
  type: string
  description: "Order status (pending, shipped, or delivered)"
Good:
yaml
status:
  type: string
  enum: [pending, shipped, delivered]
  description: "Current order status"
如果字段仅有一组有限的可选值,则必须定义
enum
。绝不能对受约束的值直接使用纯
string
类型。
错误:
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
required
array to prevent AI agents from "guessing" optional parameters.
yaml
properties:
  name:
    type: string
  email:
    type: string
  age:
    type: integer
required:
  - name
  - email
始终在 schema 的
required
数组中明确列出必填字段,避免 AI Agent“猜测”哪些参数是可选的。
yaml
properties:
  name:
    type: string
  email:
    type: string
  age:
    type: integer
required:
  - name
  - email

Rule 11: API-Level Identity (info.description)

规则 11:API 级标识(
info.description
)

The
info.description
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.
Every API must have a non-empty
info.description
that explains the API's domain, capabilities, and intended use cases.
Bad:
yaml
info:
  title: Core Services API Reference
  version: 1.0.0
Good:
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
字段是 AI Agent 首次进行 API 级发现时使用的信号。在众多 API 中进行选择时,该描述决定 Agent 是否选中了正确的 API。
每个 API 都必须包含非空的
info.description
,用于说明 API 的业务域、能力和预期用例。
错误:
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
(机械性 + 语义性)

  1. Open the API spec and find the
    info.title
    field
  2. If it already ends with 'API', no change needed
  3. Otherwise, rename to a clear, descriptive title ending with 'API':
    • Tokenization
      →
      Tokenization API
    • ObjectStore
      →
      Object Store API
    • ARM REST services
      →
      ARM REST Services API
    • Exchange - XAPI Service
      →
      Exchange Experience API
    • Edge Security Policies
      →
      Anypoint Security Policies API
    • Core Services API Reference
      →
      Access Management API
  4. Avoid trailing suffixes like 'Service', 'Reference', 'xAPI', or version numbers before 'API'
  5. Use title case for the name
  1. 打开 API 规范并找到
    info.title
    字段
  2. 如果标题已经以
    API
    结尾,则无需更改
  3. 否则,将其重命名为清晰且描述性的标题,并以
    API
    结尾:
    • Tokenization
      →
      Tokenization API
    • ObjectStore
      →
      Object Store API
    • ARM REST services
      →
      ARM REST Services API
    • Exchange - XAPI Service
      →
      Exchange Experience API
    • Edge Security Policies
      →
      Anypoint Security Policies API
    • Core Services API Reference
      →
      Access Management API
  4. 避免使用
    Service
    、
    Reference
    、
    xAPI
    或版本号等尾缀;名称应以
    API
    结尾
  5. 使用 title case 命名

Fixing
api-version-semver
(mechanical)

修复
api-version-semver
(机械性)

  1. Open the API spec and find the
    info.version
    field
  2. Convert the current value to
    MAJOR.MINOR.PATCH
    format:
    • v1
      or
      V1
      or
      "1"
      →
      1.0.0
    • v2
      →
      2.0.0
    • 1.0
      or
      "1.0"
      →
      1.0.0
    • 0.1
      →
      0.1.0
    • 1.23
      →
      1.23.0
    • v1.0
      →
      1.0.0
    • v1.0.0
      →
      1.0.0
      (strip the
      v
      prefix)
    • v2.1.3
      →
      2.1.3
      (strip the
      v
      prefix)
  3. Remove any
    v
    or
    V
    prefix — semver does not use letter prefixes
  4. Ensure exactly three dot-separated numeric components
  1. 打开 API 规范并找到
    info.version
    字段
  2. 将当前值转换为
    MAJOR.MINOR.PATCH
    格式:
    • v1
      、
      V1
      或
      1
      →
      1.0.0
    • v2
      →
      2.0.0
    • 1.0
      或
      1.0
      →
      1.0.0
    • 0.1
      →
      0.1.0
    • 1.23
      →
      1.23.0
    • v1.0
      →
      1.0.0
    • v1.0.0
      →
      1.0.0
      (移除
      v
      前缀)
    • v2.1.3
      →
      2.1.3
      (移除
      v
      前缀)
  3. 移除所有
    v
    或
    V
    前缀——semver 不使用字母前缀
  4. 确保恰好包含三个以点分隔的数字部分

Fixing
api-info-description
(semantic)

修复
api-info-description
(语义性)

  1. Read the API spec to identify: the
    info.title
    , all paths, and the main operations
  2. Determine the API's domain (e.g., security, deployment, monitoring, API management)
  3. Write a 2-3 sentence description that answers: What does this API manage? What are its key capabilities? Who or what consumes it?
  4. Add the
    description
    field under
    info
    using YAML block scalar (
    >
    ) for readability
  5. Avoid generic descriptions like "This API provides endpoints" — be specific about the domain
  1. 阅读 API 规范,以识别
    info.title
    、所有路径和主要操作
  2. 确定 API 的业务域,例如 security、deployment、monitoring 或 API management
  3. 编写 2 至 3 句话的描述,回答以下问题:该 API 管理什么?其关键能力是什么?哪些人或系统会使用它?
  4. 使用 YAML 块标量(
    >
    )在
    info
    下添加
    description
    字段,以提高可读性
  5. 避免使用“该 API 提供端点”之类的泛化描述——应具体说明业务域

Fixing
operation-id-camel-case
(mechanical + semantic)

修复
operation-id-camel-case
(机械性 + 语义性)

  1. If
    operationId
    is missing: generate one from the HTTP method + path (e.g.,
    GET /users/{id}
    →
    getUserById
    )
  2. If
    operationId
    exists but is snake_case or generic: rename to descriptive camelCase
  3. Use the pattern:
    verbNoun
    or
    verbNounQualifier
    (e.g.,
    listEnvironments
    ,
    createDeployment
    ,
    getApplicationStatus
    )
  4. The helper script
    scripts/add_operation_ids.py
    can generate initial IDs;
    scripts/improve_operation_ids.py
    can improve existing ones
  1. 如果缺少
    operationId
    ,则根据 HTTP 方法和路径生成,例如
    GET /users/{id}
    →
    getUserById
  2. 如果
    operationId
    已存在,但采用 snake_case 或名称过于泛化,则将其重命名为描述性的 camelCase
  3. 使用
    verbNoun
    或
    verbNounQualifier
    模式,例如
    listEnvironments
    、
    createDeployment
    、
    getApplicationStatus
  4. 辅助脚本
    scripts/add_operation_ids.py
    可以生成初始 ID;
    scripts/improve_operation_ids.py
    可以改进现有 ID

Fixing
operation-description
(semantic)

修复
operation-description
(语义性)

  1. Read the operation's path, method, parameters, and request/response schemas
  2. Write a description that explains what the operation does, not just restating the path
  3. Include relevant business context: preconditions, side effects, related operations
  4. The helper script
    scripts/add_descriptions.py
    can add placeholder descriptions that should then be reviewed
  1. 阅读操作的路径、方法、参数以及请求和响应 schema
  2. 编写描述以说明该操作执行的内容,而不只是复述路径
  3. 包含相关的业务上下文:前置条件、副作用和相关操作
  4. 辅助脚本
    scripts/add_descriptions.py
    可以添加占位 description,之后仍需进行审查

Fixing
operation-examples
(mechanical + semantic)

修复
operation-examples
(机械性 + 语义性)

  1. For each operation missing examples, look at the response schema to understand the shape
  2. Create a realistic example that covers the main fields
  3. Add it under the response's
    content.application/json.examples
    (or the appropriate media type)
  4. The helper script
    scripts/add_examples.py
    can generate examples from schemas
  5. The helper script
    scripts/fix_delete_head_examples.py
    handles DELETE/HEAD operations that may not need response body examples
  1. 对于缺少示例的每个操作,查看响应 schema 以了解其结构
  2. 创建覆盖主要字段的逼真示例
  3. 将其添加在响应的
    content.application/json.examples
    下,或适当的媒体类型下
  4. 辅助脚本
    scripts/add_examples.py
    可以根据 schema 生成示例
  5. 辅助脚本
    scripts/fix_delete_head_examples.py
    用于处理可能不需要响应正文示例的 DELETE/HEAD 操作

Fixing
input-types-described
(semantic)

修复
input-types-described
(语义性)

  1. For each parameter missing a description, examine its name, type, and where it's used
  2. Write a description that explains what the parameter controls and valid values
  3. For path parameters: explain what resource it identifies
  4. For query parameters: explain filtering/pagination behavior and defaults
  1. 对于缺少 description 的每个参数,检查其名称、类型及使用位置
  2. 编写 description,说明该参数控制什么内容以及有效值
  3. 对于路径参数:说明其标识的资源
  4. 对于查询参数:说明过滤或分页行为以及默认值

Fixing
output-response-description
(semantic)

修复
output-response-description
(语义性)

  1. For each response missing a description, examine the status code and response schema
  2. Write a description that explains what the response represents and when it's returned
  3. For error responses (4xx/5xx): include what triggers the error and how to resolve it
  1. 对于缺少 description 的每个响应,检查状态码和响应 schema
  2. 编写 description,说明该响应表示什么以及在何时返回
  3. 对于错误响应(4xx/5xx):说明触发错误的原因以及解决方法

Fixing
request-body-description
(semantic)

修复
request-body-description
(语义性)

  1. For each request body missing a description, examine the schema and the operation's purpose
  2. Write a description that explains what data the caller must provide and any constraints
  1. 对于缺少 description 的每个请求正文,检查 schema 和操作用途
  2. 编写 description,说明调用方必须提供哪些数据以及相关约束

Fixing
output-types-described
(semantic)

修复
output-types-described
(语义性)

Same approach as
output-response-description
— ensure every response has a description explaining the returned data.
采用与
output-response-description
相同的方法——确保每个响应都有 description,用于说明返回的数据。

General Fix Workflow

通用修复工作流

When fixing violations across multiple APIs:
  1. Run Pass 2 validation on the target API
  2. Parse the JSON output to identify violations grouped by rule
  3. Fix violations one rule type at a time (batch similar fixes)
  4. Re-run Pass 2 to verify fixes — iterate until clean
  5. Move to the next API
修复多个 API 中的违规项时:
  1. 对目标 API 执行第 2 轮验证
  2. 解析 JSON 输出,按规则归类违规项
  3. 每次修复一种规则类型(批量修复相似问题)
  4. 重新执行第 2 轮验证以确认修复——持续迭代直至通过
  5. 移至下一个 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-plugin

Automated 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/oas
This 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.yaml
This validates:
  1. API title ends with 'API' (Rule 2)
  2. Semantic versioning in info.version (Rule 3)
  3. Descriptive operation IDs (Rule 4)
  4. Comprehensive descriptions with context (Rule 5)
  5. Examples in requests and responses (Rule 6)
  6. Type documentation for all properties (Rule 7)
  7. Output types fully documented (Rule 8)
  8. No naked strings - enums required (Rule 9)
  9. Required fields explicitly listed (Rule 10)
  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
此步骤将验证:
  1. API 标题以
    API
    结尾(规则 2)
  2. info.version
    使用 Semantic Versioning(规则 3)
  3. operation ID 具备描述性(规则 4)
  4. description 完整且包含上下文(规则 5)
  5. 请求和响应中包含示例(规则 6)
  6. 所有属性都有类型文档(规则 7)
  7. 输出类型文档完整(规则 8)
  8. 不存在裸字符串——必须使用 enum(规则 9)
  9. 明确列出必填字段(规则 10)
  10. 存在 API 级标识——提供
    info.description
    (规则 11)
该工具将:
  • 解析 OAS 文件
  • 检查所有验证规则
  • 生成包含违规项的详细报告
  • 以状态码 0(通过)或 1(失败)退出

Complete Validation Workflow

完整验证工作流

The recommended workflow for validating an API specification:
  1. Check format: Ensure spec is OAS (not RAML) - convert if needed
  2. Pass 1 - Basic validation: Run
    anypoint-cli-v4 api-project validate  --json --location=./path
  3. Fix syntax errors: Address any errors from Pass 1 before continuing
  4. Pass 2 - Compliance validation: Run with
    --local-ruleset skills/api-spec-validator/scripts/ruleset.yaml
  5. Review violations: Check the detailed report for rule violations
  6. Fix violations: Update spec to address each violation
  7. Re-run Pass 2: Verify all violations are resolved
验证 API 规范时推荐采用以下工作流:
  1. 检查格式:确保规范采用 OAS(而非 RAML)——必要时进行转换
  2. 第 1 轮——基础验证:运行
    anypoint-cli-v4 api-project validate  --json --location=./path
  3. 修复语法错误:在继续之前解决第 1 轮发现的全部错误
  4. 第 2 轮——合规性验证:使用
    --local-ruleset skills/api-spec-validator/scripts/ruleset.yaml
    运行
  5. 审查违规项:检查详细报告中的规则违规情况
  6. 修复违规项:更新规范以解决每项违规问题
  7. 重新执行第 2 轮验证:确认所有违规项均已解决

Manual Review Checklist

手动审查清单

When reviewing specs manually:
  1. Check if spec is in RAML format - if so, translate to OAS first
  2. Check each endpoint has
    operationId
    ,
    description
    , and examples
  3. Verify operation IDs are descriptive (not generic)
  4. Look for legacy field names requiring mapping explanations
  5. Identify slow/rate-limited endpoints needing warnings
  6. Check for cryptic paths needing AI aliases in
    summary
  7. Check 400 responses for error codes - add recovery instructions
  8. Ensure all string fields with limited options use
    enum
  9. Verify all schemas have explicit
    required
    arrays
  10. Confirm all properties have meaningful descriptions
手动审查规范时:
  1. 检查规范是否采用 RAML 格式——如是,先将其转换为 OAS
  2. 检查每个端点是否都有
    operationId
    、
    description
    和示例
  3. 验证 operation ID 是否具备描述性,而不是泛化名称
  4. 找出需要映射说明的旧版字段名
  5. 找出需要添加警告的慢速或受速率限制端点
  6. 找出需要使用
    summary
    添加 AI 别名的隐晦路径
  7. 检查 400 响应中的错误代码——添加恢复说明
  8. 确保所有仅具有有限选项的字符串字段都使用
    enum
  9. 验证所有 schema 都明确包含
    required
    数组
  10. 确认所有属性都有 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:
  1. Run Pass 1 (basic OAS validation)
  2. If Pass 1 succeeds, run Pass 2 (compliance validation)
  3. 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. 执行第 1 轮验证(基础 OAS 验证)
  2. 如果第 1 轮成功,则执行第 2 轮验证(合规性验证)
  3. 提供违规项摘要和修复建议

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

需要修复的常见问题

  1. Missing API description: Add
    info.description
    explaining domain and capabilities
  2. RAML format: Convert RAML specs to OAS before validation
  3. Generic operation IDs: Replace
    getData
    with
    getUserProfile
  4. Missing enums: Add enums for status codes, types, categories
  5. Undocumented fields: Add descriptions explaining purpose and usage
  6. Missing required arrays: Explicitly list which fields are mandatory
  7. Cryptic paths: Add summary aliases for
    /rpc/
    or
    /action/
    style paths
  8. Undocumented 400 errors: Add recovery instructions for error codes
  1. 缺少 API description:添加
    info.description
    ,说明业务域和能力
  2. RAML 格式:验证前将 RAML 规范转换为 OAS
  3. 泛化的 operation ID:将
    getData
    替换为
    getUserProfile
  4. 缺少 enum:为状态代码、类型和类别添加 enum
  5. 未记录字段:添加 description,说明用途和使用方式
  6. 缺少 required 数组:明确列出哪些字段为必填字段
  7. 隐晦路径:为
    /rpc/
    或
    /action/
    风格的路径添加 summary 别名
  8. 未记录的 400 错误:为错误代码添加恢复说明

Output Format

输出格式

When validating with
anypoint-cli-v4
, the tool provides a structured report:
Validating 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
When summarizing results for users, organize by rule type and provide actionable fixes.
使用
anypoint-cli-v4
进行验证时,该工具会提供结构化报告:
Validating 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:
  • references/example-good-spec.yaml
    - Example of a fully compliant spec with all best practices
  • references/example-violations.yaml
    - Common mistakes and how to fix them
有关详细示例和指南,请参阅:
  • references/example-good-spec.yaml
    - 包含所有最佳实践的完全合规规范示例
  • references/example-violations.yaml
    - 常见错误及其修复方式