关于 openapi
面向 API 设计与开发者的 OpenAPI 核心知识技能,涵盖规范结构、Schema、质量检查和代码生成,帮助维护 API 契约并供前端使用。
主要功能
- 01介绍 OpenAPI 基本结构
- 02说明 Schema 类型与校验
- 03列出规范设计反模式
- 04提供规范验证与契约测试示例
- 05展示 TypeScript 类型和客户端生成
适用场景
- 01定义 API 请求与响应契约
- 02检查规范并排查验证错误
- 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.mdspecification.mdtools.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