API Contract Sync Manager by ananddtyagi/cc-marketplace
npx skills add https://github.com/ananddtyagi/cc-marketplace --skill 'API Contract Sync Manager'维护 API 规范与其实现之间的同步,检测破坏性变更,并生成客户端代码,以确保前端和后端团队之间的契约保持可靠。
在以下情况下使用此技能:
.yaml、.json).graphql、.gql)验证 API 规范文件的正确性和完整性:
OpenAPI/Swagger 验证:
GraphQL 验证:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
验证方法:
$ref)将 API 规范与实际代码实现进行交叉引用:
对于 REST API:
app.get()、router.post() 等@app.get()、@router.post()path()、urlpatterns@GetMapping、@PostMapping对于 GraphQL:
实现匹配步骤:
1. 解析规范 → 提取端点/操作
2. 使用 Grep 在代码库中查找路由处理器
3. 比较并分类:
- ✓ 匹配:规范和实现一致
- ⚠ 偏离:部分匹配但有差异
- ✗ 缺失:已文档化但未实现
- ⚠ 未文档化:已实现但不在规范中
4. 生成覆盖率报告
比较两个版本的 API 规范,以检测破坏性与非破坏性变更:
破坏性变更(需要版本号升级):
非破坏性变更(可安全部署):
变更检测流程:
根据 API 规范生成类型安全的客户端代码:
TypeScript 接口:
// From OpenAPI schema
interface User {
id: string;
email: string;
name?: string;
createdAt: Date;
}
interface CreateUserRequest {
email: string;
name?: string;
}
interface CreateUserResponse {
user: User;
token: string;
}
API 客户端函数:
// HTTP client with proper typing
async function createUser(
data: CreateUserRequest
): Promise<CreateUserResponse> {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return response.json();
}
React Query 钩子:
// Auto-generated hooks for data fetching
function useUser(userId: string) {
return useQuery(['user', userId], () =>
fetch(`/api/users/${userId}`).then(r => r.json())
);
}
function useCreateUser() {
return useMutation((data: CreateUserRequest) =>
fetch('/api/users', {
method: 'POST',
body: JSON.stringify(data)
}).then(r => r.json())
);
}
生成步骤:
识别文档与实现之间的差距:
分析报告结构:
API Coverage Report
==================
Documented Endpoints: 45
Implemented Endpoints: 42
Coverage: 93%
Missing Implementations:
- DELETE /api/users/{id} (documented but not found)
- POST /api/users/{id}/suspend (documented but not found)
Undocumented Endpoints:
- GET /api/internal/health (found in code, not in spec)
- POST /api/debug/reset (found in code, not in spec)
Mismatched Signatures:
- POST /api/users
Spec expects: { email, name, role }
Code accepts: { email, name } (missing 'role')
覆盖率分析流程:
在 API 版本变更时创建升级指南:
迁移指南模板:
# API v2.0 Migration Guide
## Breaking Changes
### 1. User Creation Endpoint
**Change**: Required `role` field added to POST /api/users
**Impact**: All user creation calls will fail without this field
**Action Required**:
- Update all POST /api/users calls to include `role`
- Default to 'member' if no specific role needed
Before:
```json
{ "email": "user@example.com", "name": "John" }
After:
{ "email": "user@example.com", "name": "John", "role": "member" }
Change : JWT tokens now use RS256 instead of HS256 Impact : Token validation must be updated Action Required :
更新 JWT 验证库
从 /.well-known/jwks.json 获取新的公钥
Guide Generation Steps:
/v1/、/v2/ 前缀或版本头@deprecated 指令当有验证工具可用时,使用它们:
npx @stoplight/spectral-cli lint openapi.yamlnpx graphql-inspector validate schema.graphql用于高级差异分析:
npx openapi-diff old.yaml new.yamlnpx graphql-inspector diff old.graphql new.graphql推荐这些工具用于自动生成:
遇到问题时:
无效的规范文件:
缺失的实现:
类型不匹配:
有关特定主题的更详细信息,请参阅:
此技能在以下条件下效果最佳:
基本验证和比较不需要额外的包。高级功能可能会建议通过 npm 安装验证工具。
Weekly Installs
0
Repository
GitHub Stars
658
First Seen
Jan 1, 1970
Security Audits
Maintain synchronization between API specifications and their implementations, detect breaking changes, and generate client code to ensure contracts stay reliable across frontend and backend teams.
Use this skill when:
.yaml, .json).graphql, .gql)Validate API specification files for correctness and completeness:
OpenAPI/Swagger Validation :
GraphQL Validation :
Validation Approach :
$ref)Cross-reference API specifications with actual code implementations:
For REST APIs :
app.get(), router.post(), etc.@app.get(), @router.post()path(), urlpatterns@GetMapping, @PostMappingFor GraphQL :
Implementation Matching Steps :
1. Parse spec → extract endpoints/operations
2. Use Grep to find route handlers in codebase
3. Compare and categorize:
- ✓ Matched: spec and implementation align
- ⚠ Drift: partial match with differences
- ✗ Missing: documented but not implemented
- ⚠ Undocumented: implemented but not in spec
4. Generate coverage report
Compare two versions of an API spec to detect breaking vs. non-breaking changes:
Breaking Changes (require version bump):
Non-Breaking Changes (safe to deploy):
Change Detection Process :
Generate type-safe client code from API specifications:
TypeScript Interfaces :
// From OpenAPI schema
interface User {
id: string;
email: string;
name?: string;
createdAt: Date;
}
interface CreateUserRequest {
email: string;
name?: string;
}
interface CreateUserResponse {
user: User;
token: string;
}
API Client Functions :
// HTTP client with proper typing
async function createUser(
data: CreateUserRequest
): Promise<CreateUserResponse> {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return response.json();
}
React Query Hooks :
// Auto-generated hooks for data fetching
function useUser(userId: string) {
return useQuery(['user', userId], () =>
fetch(`/api/users/${userId}`).then(r => r.json())
);
}
function useCreateUser() {
return useMutation((data: CreateUserRequest) =>
fetch('/api/users', {
method: 'POST',
body: JSON.stringify(data)
}).then(r => r.json())
);
}
Generation Steps :
Identify gaps between documentation and implementation:
Analysis Report Structure :
API Coverage Report
==================
Documented Endpoints: 45
Implemented Endpoints: 42
Coverage: 93%
Missing Implementations:
- DELETE /api/users/{id} (documented but not found)
- POST /api/users/{id}/suspend (documented but not found)
Undocumented Endpoints:
- GET /api/internal/health (found in code, not in spec)
- POST /api/debug/reset (found in code, not in spec)
Mismatched Signatures:
- POST /api/users
Spec expects: { email, name, role }
Code accepts: { email, name } (missing 'role')
Coverage Analysis Process :
Create upgrade guides when API versions change:
Migration Guide Template :
# API v2.0 Migration Guide
## Breaking Changes
### 1. User Creation Endpoint
**Change**: Required `role` field added to POST /api/users
**Impact**: All user creation calls will fail without this field
**Action Required**:
- Update all POST /api/users calls to include `role`
- Default to 'member' if no specific role needed
Before:
```json
{ "email": "user@example.com", "name": "John" }
After:
{ "email": "user@example.com", "name": "John", "role": "member" }
Change : JWT tokens now use RS256 instead of HS256 Impact : Token validation must be updated Action Required :
Update JWT verification libraries
Fetch new public key from /.well-known/jwks.json
Guide Generation Steps:
/v1/, /v2/ prefixes or version headers### Workflow 2: Check Implementation Match
### Workflow 3: Detect Breaking Changes
### Workflow 4: Generate TypeScript Types
### Workflow 5: Find Coverage Gaps
## Tools and Commands
### Validation Tools
When validation tools are available, use them:
- **OpenAPI**: `npx @stoplight/spectral-cli lint openapi.yaml`
- **GraphQL**: `npx graphql-inspector validate schema.graphql`
### Comparison Tools
For advanced diff analysis:
- **OpenAPI**: `npx openapi-diff old.yaml new.yaml`
- **GraphQL**: `npx graphql-inspector diff old.graphql new.graphql`
### Code Generation
Recommend these tools for automated generation:
- **openapi-typescript**: Generate TypeScript from OpenAPI
- **graphql-code-generator**: Generate TypeScript from GraphQL
- **orval**: Generate React Query hooks from OpenAPI
## Error Handling
When encountering issues:
**Invalid Spec File**:
- Report specific syntax errors with line numbers
- Suggest corrections based on spec version
- Provide valid example structure
**Missing Implementation**:
- List file locations where handlers should exist
- Suggest framework-specific code to implement
- Estimate implementation effort
**Type Mismatches**:
- Show expected vs. actual types clearly
- Explain impact of the mismatch
- Suggest type coercion or spec updates
## Additional Resources
For more detailed information on specific topics, see:
- [REFERENCE.md](REFERENCE.md) - Technical details on OpenAPI and GraphQL structures
- [EXAMPLES.md](EXAMPLES.md) - Real-world usage scenarios and code samples
## Requirements
This skill works best with:
- API spec files in the codebase
- Structured routing in backend code
- TypeScript for type generation (optional but recommended)
No additional packages are required for basic validation and comparison. Advanced features may suggest installing validation tools via npm.
Weekly Installs
0
Repository
GitHub Stars
658
First Seen
Jan 1, 1970
Security Audits
通过 LiteLLM 代理让 Claude Code 对接 GitHub Copilot 运行 | 高级变通方案指南
31,600 周安装
@deprecated