用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/microwind/ai-skills --skill api命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
基于 SOC 职业分类
正在显示 SKILL.md
| name | API文档生成与管理 |
| description | 当生成API文档时,分析文档结构,优化文档质量,解决版本同步。验证文档架构,设计自动化流程,和最佳实践。 |
| license | MIT |
API文档是接口开发的重要组成部分,高质量的文档能够提高开发效率、降低沟通成本、提升用户体验。不当的文档管理会导致信息过时、维护困难、协作效率低下。
核心原则: 好的API文档应该准确完整、易于理解、及时更新、自动化生成。坏的文档会导致使用困难、错误频发、维护成本高。
始终:
触发短语:
❌ 文档信息过时
❌ 文档质量差
❌ 维护成本高
❌ 用户体验差
# openapi.yaml
openapi: 3.0.3
info:
title: 用户管理API
description: 用户注册、登录、信息管理等功能的RESTful API
version: 1.0.0
contact:
name: API支持团队
email: api-support@example.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
servers:
- url: https://api.example.com/v1
description: 生产环境
- url: https://staging-api.example.com/v1
description: 测试环境
- url: http://localhost:3000/v1
description: 开发环境
tags:
- name: 用户管理
description: 用户相关操作
- name: 认证授权
description: 登录注册相关
paths:
/users:
get:
tags:
- 用户管理
[]
// SwaggerConfig.java
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("用户管理API")
.description("用户注册、登录、信息管理等功能的RESTful API")
.version("1.0.0")
.contact(new Contact()
.name("API支持团队")
.email("api-support@example.com"))
.license(new License()
.name("MIT")
.url("https://opensource.org/licenses/MIT")))
.servers(List.of(
new Server().url("https://api.example.com/v1").description("生产环境"),
().url().description(),
().url().description()
))
.addSecurityItem( ().addList())
.components( .swagger.v3.oas.models.Components()
.addSecuritySchemes(, ()
.type(SecurityScheme.Type.HTTP)
.scheme()
.bearerFormat()));
}
}
io.swagger.v3.oas.annotations.Operation;
io.swagger.v3.oas.annotations.Parameter;
io.swagger.v3.oas.annotations.media.Content;
io.swagger.v3.oas.annotations.media.Schema;
io.swagger.v3.oas.annotations.responses.ApiResponse;
io.swagger.v3.oas.annotations.responses.ApiResponses;
io.swagger.v3.oas.annotations.security.SecurityRequirement;
org.springframework.http.ResponseEntity;
org.springframework.web.bind.annotation.*;
javax.validation.Valid;
java.util.List;
{
UserService userService;
{
.userService = userService;
}
ResponseEntity<UserListResponse> {
userService.getUsers(page, limit, search);
ResponseEntity.ok(response);
}
ResponseEntity<User> {
userService.createUser(request);
ResponseEntity.status().body(user);
}
ResponseEntity<User> {
userService.getUserById(userId);
ResponseEntity.ok(user);
}
ResponseEntity<User> {
userService.updateUser(userId, request);
ResponseEntity.ok(user);
}
}
io.swagger.v3.oas.annotations.media.Schema;
{
Long id;
String username;
String email;
String fullName;
String avatar;
LocalDateTime createdAt;
LocalDateTime updatedAt;
}
{
String username;
String email;
String password;
String fullName;
}
#!/usr/bin/env python3
import json
import yaml
import requests
from typing import Dict, List, Any
from pathlib import Path
class APIDocumentationGenerator:
def __init__(self, config_file: str = "api-docs-config.json"):
self.config = self.load_config(config_file)
self.output_dir = Path(self.config.get("output_dir", "docs"))
self.output_dir.mkdir(exist_ok=True)
def load_config(self, config_file: str) -> Dict:
"""加载配置文件"""
try:
with open(config_file, 'r') as f:
return json.load(f)
except FileNotFoundError:
return self.create_default_config(config_file)
def create_default_config(self, config_file: str) -> Dict:
"""创建默认配置"""
default_config = {
"output_dir": ,
: [, , ],
: [
{
: ,
: ,
:
}
],
: {
: ,
:
},
: {
: ,
: ,
:
}
}
(config_file, ) f:
json.dump(default_config, f, indent=)
default_config
() -> :
:
response = requests.get(url, timeout=)
response.raise_for_status()
content_type = response.headers.get(, )
content_type:
response.json()
content_type content_type:
yaml.safe_load(response.text)
:
:
response.json()
:
yaml.safe_load(response.text)
requests.RequestException e:
()
{}
() -> []:
errors = []
spec:
errors.append()
errors
required_fields = [, , ]
field required_fields:
field spec:
errors.append()
spec:
info = spec[]
info_required = [, ]
field info_required:
field info:
errors.append()
spec:
paths = spec[]
paths:
errors.append()
:
path, path_item paths.items():
method, operation path_item.items():
method.upper() [, , , , ]:
operation operation:
errors.append()
errors
() -> :
examples = {}
spec:
examples
path, path_item spec[].items():
method, operation path_item.items():
method.upper() [, , , , ]:
operation_id = operation.get(, )
curl_example = .generate_curl_example(method, path, operation)
js_example = .generate_js_example(method, path, operation)
python_example = .generate_python_example(method, path, operation)
examples[operation_id] = {
: curl_example,
: js_example,
: python_example
}
examples
() -> :
base_url =
url =
curl_cmd =
headers = []
operation:
param operation[]:
param.get() == :
headers.append()
operation:
headers.append()
headers:
curl_cmd += + .join(headers)
method.upper() [, , ] operation:
request_body = operation[]
request_body:
content_type = (request_body[].keys())[]
headers.append()
example_body = .generate_example_body(request_body[][content_type])
curl_cmd +=
curl_cmd
() -> :
base_url =
url =
js_code =
headers = {}
operation:
headers[] =
method.upper() [, , ] operation:
headers[] =
headers:
js_code +=
method.upper() [, , ] operation:
request_body = operation[]
request_body:
content_type = (request_body[].keys())[]
example_body = .generate_example_body(request_body[][content_type])
js_code +=
js_code +=
js_code
() -> :
base_url =
url =
python_code =
headers = {}
operation:
headers[] =
method.upper() [, , ] operation:
headers[] =
headers:
python_code +=
python_code +=
python_code
() -> :
content_spec:
json.dumps(content_spec[], indent=)
content_spec:
.generate_example_from_schema(content_spec[])
() -> :
schema.get() == :
example = {}
properties = schema.get(, {})
prop_name, prop_spec properties.items():
prop_name schema.get(, []):
example[prop_name] = .generate_example_from_schema(prop_spec)
json.dumps(example, indent=)
schema.get() == :
schema:
schema[] == :
schema[] == :
schema.get() == :
(schema.get(, ))
schema.get() == :
schema.get() == :
() -> :
html_template =
examples_html =
operation_id, example_set examples.items():
examples_html +=
html_template.(
title=spec.get(, {}).get(, ),
description=spec.get(, {}).get(, ),
spec_json=json.dumps(spec).replace(, ),
examples_html=examples_html
)
() -> :
md_content =
"""
# 添加端点信息
if 'paths' in spec:
for path, path_item in spec['paths'].items():
md_content += f"### {path}\n\n"
for method, operation in path_item.items():
if method.upper() in ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']:
operation_id = operation.get('operationId', f"{method}_{path}")
summary = operation.get('summary', '')
description = operation.get('description', '')
md_content += f"#### {method.upper()} {path}\n\n"
if summary:
md_content += f"**摘要**: {summary}\n\n"
if description:
md_content += f"**描述**: {description}\n\n"
# 添加代码示例
if operation_id in examples:
example_set = examples[operation_id]
md_content += "**代码示例**:\n\n"
md_content += "```bash\n" + example_set['curl'] + "\n```\n\n"
md_content += "```javascript\n" + example_set['javascript'] + "\n```\n\n"
md_content += "```python\n" + example_set['python'] + "\n```\n\n"
return md_content
def generate_documentation(self):
"""生成文档"""
print("开始生成API文档...")
for api_source in self.config.get('api_sources', []):
print(f"处理API: {api_source['name']}")
# 获取API规范
spec = self.fetch_openapi_spec(api_source['url'])
# 验证规范
errors = self.validate_spec(spec)
if errors:
print(f"API规范验证失败: {errors}")
continue
# 生成示例
examples = self.generate_examples(spec)
# 生成不同格式的文档
formats = self.config.get('formats', ['html', 'markdown'])
for format_type in formats:
if format_type == 'html':
html_content = self.generate_html_docs(spec, examples)
output_file = self.output_dir / f"{api_source['name'].lower().replace(' ', '-')}.html"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html_content)
print(f"生成HTML文档: {output_file}")
elif format_type == 'markdown':
md_content = self.generate_markdown_docs(spec, examples)
output_file = self.output_dir / f"{api_source['name'].lower().replace(' ', '-')}.md"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(md_content)
print(f"生成Markdown文档: {output_file}")
print("文档生成完成!")
def main(): """主函数""" import argparse
parser = argparse.ArgumentParser(description='API文档生成器')
parser.add_argument('--config', default='api-docs-config.json', help='配置文件路径')
parser.add_argument('--output', help='输出目录')
args = parser.parse_args()
generator = APIDocumentationGenerator(args.config)
if args.output:
generator.output_dir = Path(args.output)
generator.output_dir.mkdir(exist_ok=True)
generator.generate_documentation()
if name == "main": main()
## 最佳实践
### 文档设计
- **统一规范**: 使用OpenAPI/Swagger标准
- **完整描述**: 提供详细的参数说明和示例
- **版本管理**: 明确的版本控制和变更日志
- **多语言支持**: 支持中英文文档
### 自动化流程
- **代码生成**: 从注解自动生成文档
- **持续更新**: CI/CD流程中自动更新文档
- **验证检查**: 自动验证文档完整性和准确性
- **多格式输出**: 支持HTML、PDF、Markdown等格式
### 质量保证
- **示例验证**: 确保示例代码可用
- **一致性检查**: 验证文档与实际接口一致性
- **完整性检查**: 确保所有接口都有文档
- **定期审查**: 定期检查和更新文档内容
### 用户体验
- **交互式文档**: 提供在线测试功能
- **代码示例**: 多语言的代码示例
- **快速入门**: 提供快速开始指南
- **错误处理**: 详细的错误响应说明
## 相关技能
- [Git工作流管理](./git-workflows/) - 文档版本控制
- [Docker Compose编排](./docker-compose/) - 文档服务部署
- [代码格式化](./code-formatter/) - 文档代码格式化
- [版本管理器](./version-manager/) - API版本管理