mcpField
O
openapi

openapi

github.com/claude-dev-suite开发4648 次安装6 天前更新
代码仓库

关于 openapi

面向 API 设计与开发者的 OpenAPI 核心知识技能,涵盖规范结构、Schema、质量检查和代码生成,帮助维护 API 契约并供前端使用。

主要功能

  1. 01介绍 OpenAPI 基本结构
  2. 02说明 Schema 类型与校验
  3. 03列出规范设计反模式
  4. 04提供规范验证与契约测试示例
  5. 05展示 TypeScript 类型和客户端生成

适用场景

  1. 01定义 API 请求与响应契约
  2. 02检查规范并排查验证错误
  3. 03为前端生成类型或客户端

MCP 相关

README 提到可通过 mcp__documentation__fetch_docs 获取 OpenAPI 深入文档;未说明该技能本身如何连接 MCP。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill openapi

安装后在 Claude Code 中输入/openapi确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

quick-ref/
frontend-integration.md
specification.md
tools.md

详细介绍

OpenAPI 核心知识

深入了解:使用 mcp__documentation__fetch_docs 并将 technology 设为 openapi,获取全面的文档。

基本结构

openapi: 3.1.0
info:
  title: User API
  version: 1.0.0
  description: API for managing users

servers:
  - url: https://api.example.com/v1

paths:
  /users:
    get:
      summary: List users
      operationId: listUsers
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: List of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
    post:
      summary: Create user
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUser'
      responses:
        '201':
          description: User created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

  /users/{id}:
    get:
      summary: Get user by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: User found
        '404':
          description: User not found

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        email:
          type: string
          format: email
      required: [id, name, email]

    CreateUser:
      type: object
      properties:
        name:
          type: string
        email:
          type: string
          format: email
      required: [name, email]

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []

Schema 类型

# String with validation
type: string
minLength: 1
maxLength: 100
pattern: '^[a-zA-Z]+$'
format: email | date | date-time | uri | uuid

# Number
type: integer
minimum: 0
maximum: 100

# Enum
type: string
enum: [active, inactive, pending]

# Array
type: array
items:
  type: string
minItems: 1
maxItems: 10

# Object
type: object
additionalProperties: false

何时不应使用此技能

  • GraphQL API 文档(使用 graphql 技能)
  • tRPC 类型安全 API(使用 trpc 技能)
  • 生成 API 客户端(使用 openapi-codegen 技能)
  • Spring Boot API 文档(使用 springdoc-openapi 技能)
  • 代码优先的 API 开发(考虑使用注解/装饰器)

反模式

反模式问题所在解决方案
缺少响应 Schema没有类型安全性,文档质量差为所有响应定义 Schema
Schema 中没有示例API 难以理解为所有 Schema 添加 example 或 examples
只使用 object,不定义属性丢失类型信息明确定义带类型的属性
未定义错误响应API 契约不完整记录 4xx 和 5xx 响应
将服务 URL 硬编码规范中包含特定环境的配置使用服务变量或多个服务
缺少 required 字段API 契约含糊不清明确标记所有必填字段
Schema 定义重复难以维护使用 $ref 和组件
未定义安全方案身份验证方式不明确在组件中定义安全方案
缺少 operationId代码生成效果差为每个端点添加唯一的 operationId
到处使用 additionalProperties: true失去验证方面的优势除非确有需要,否则将其设为 false

快速故障排查

问题可能原因解决方案
规范中出现验证错误YAML/JSON 语法无效使用 @redocly/cli lint 或 Swagger Editor
代码生成失败缺少 operationId 或引用无效添加 operationId,并确认所有 $ref 均可解析
Swagger UI 无法加载CORS 问题或规范无效检查浏览器控制台并验证规范
生成的代码中存在类型错误Schema 与实现不匹配确保 Schema 与实际 API 响应一致
生成的类型中缺少字段Schema 未定义所有属性在 Schema 定义中添加所有属性
出现循环引用错误Schema 自我引用使用 allOf 或重构 Schema 结构
示例验证失败示例与 Schema 不匹配确保示例符合 Schema 约束
Swagger UI 中缺少身份验证未配置安全性添加 securitySchemes 和安全要求

生产就绪

完整的错误响应
components:
  schemas:
    Error:
      type: object
      properties:
        code:
          type: string
          example: 'NOT_FOUND'
        message:
          type: string
          example: 'User not found'
        details:
          type: array
          items:
            type: object
            properties:
              field:
                type: string
              message:
                type: string
      required: [code, message]

  responses:
    BadRequest:
      description: Invalid request
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            code: 'VALIDATION_ERROR'
            message: 'Invalid input'
            details:
              - field: 'email'
                message: 'Invalid email format'

    Unauthorized:
      description: Authentication required
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

    RateLimited:
      description: Too many requests
      headers:
        X-RateLimit-Limit:
          schema:
            type: integer
        X-RateLimit-Remaining:
          schema:
            type: integer
        X-RateLimit-Reset:
          schema:
            type: integer
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

paths:
  /users:
    post:
      responses:
        '201':
          description: Created
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/RateLimited'
分页
components:
  schemas:
    PaginatedResponse:
      type: object
      properties:
        data:
          type: array
          items: {}
        pagination:
          type: object
          properties:
            page:
              type: integer
            limit:
              type: integer
            total:
              type: integer
            totalPages:
              type: integer

  parameters:
    PageParam:
      name: page
      in: query
      schema:
        type: integer
        minimum: 1
        default: 1
    LimitParam:
      name: limit
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 20

paths:
  /users:
    get:
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'
      responses:
        '200':
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/PaginatedResponse'
                  - type: object
                    properties:
                      data:
                        items:
                          $ref: '#/components/schemas/User'
代码生成
# Generate TypeScript types
npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts

# Generate client SDK
npx @openapitools/openapi-generator-cli generate \
  -i openapi.yaml \
  -g typescript-fetch \
  -o ./src/api-client

# Validate spec
npx @redocly/cli lint openapi.yaml
// Generated type usage
import type { paths, components } from './types/api';

type User = components['schemas']['User'];
type CreateUserRequest = paths['/users']['post']['requestBody']['content']['application/json'];
type UserListResponse = paths['/users']['get']['responses']['200']['content']['application/json'];
测试
// Contract testing with OpenAPI
import SwaggerParser from '@apidevtools/swagger-parser';
import { expect, test } from 'vitest';

test('OpenAPI spec is valid', async () => {
  const api = await SwaggerParser.validate('./openapi.yaml');
  expect(api.info.title).toBeDefined();
});

// API response validation
import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv({ strict: false });
addFormats(ajv);

test('GET /users returns valid response', async () => {
  const response = await fetch('/api/users');
  const data = await response.json();

  const validate = ajv.compile(userListSchema);
  expect(validate(data)).toBe(true);
});
监控指标
指标目标
规范验证错误0
破坏性变更0(semver)
文档覆盖率100%
示例覆盖率> 80%
检查清单
  • 标准错误响应 Schema
  • 已定义分页参数
  • 已记录所有响应
  • 已定义安全方案
  • 请求/响应示例
  • 可复用组件
  • 已配置代码生成
  • CI 中进行规范验证
  • 契约测试
  • 版本控制策略

前端集成

前端应用可以使用 OpenAPI 规范生成类型安全的客户端。

工作流
OpenAPI Spec → Code Generation → Type-Safe Client → Frontend App
相关技能
技能用途
HTTP 客户端Axios、Fetch、ky、ofetch 模式
OpenAPI 代码生成根据规范生成客户端
类型安全 API端到端类型安全
快速生成客户端
# Generate TypeScript types only
npx openapi-typescript ./openapi.yaml -o ./src/types/api.ts

# Generate full client
npx @openapitools/openapi-generator-cli generate \
  -i openapi.yaml \
  -g typescript-fetch \
  -o ./src/api-client

# swagger-typescript-api (simpler)
npx swagger-typescript-api -p ./openapi.yaml -o ./src/api --axios
在前端中使用类型
import type { paths, components } from './types/api';
import { createApiClient } from './api-client';

// Type-safe request/response
type User = components['schemas']['User'];
type CreateUserBody = paths['/users']['post']['requestBody']['content']['application/json'];
type UsersResponse = paths['/users']['get']['responses']['200']['content']['application/json'];

// With generated client
const api = createApiClient({ baseUrl: '/api' });
const users = await api.users.list(); // Fully typed

参考文档

评论

支持 Markdown