api-documentation by bobmatnyc/claude-mpm-skills
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill api-documentation记录 API 和代码接口的最佳实践。为每个智能体消除约 100-150 行冗余的文档指导。
def calculate_discount(price: float, discount_percent: float) -> float:
"""
计算折扣后的价格。
Args:
price: 原价(美元)(必须为正数)
discount_percent: 折扣百分比 (0-100)
Returns:
折扣后的最终价格,四舍五入到两位小数
Raises:
ValueError: 如果价格为负数或折扣 > 100
Examples:
>>> calculate_discount(100.0, 20.0)
80.0
>>> calculate_discount(50.0, 50.0)
25.0
Note:
折扣百分比上限为 100%(最低价格为 0)
"""
if price < 0:
raise ValueError("Price cannot be negative")
if discount_percent > 100:
raise ValueError("Discount cannot exceed 100%")
discount_amount = price * (discount_percent / 100)
return round(price - discount_amount, 2)
/**
* 计算折扣后的价格
*
* @param {number} price - 原价(美元)(必须为正数)
* @param {number} discountPercent - 折扣百分比 (0-100)
* @returns {number} 折扣后的最终价格,四舍五入到两位小数
* @throws {Error} 如果价格为负数或折扣 > 100
*
* @example
* calculateDiscount(100.0, 20.0)
* // returns 80.0
*
* @example
* calculateDiscount(50.0, 50.0)
* // returns 25.0
*/
function calculateDiscount(price, discountPercent) {
if (price < 0) {
throw new Error('Price cannot be negative');
}
if (discountPercent > 100) {
throw new Error('Discount cannot exceed 100%');
}
const discountAmount = price * (discountPercent / 100);
return Math.round((price - discountAmount) * 100) / 100;
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
// CalculateDiscount 使用百分比计算折扣后的价格。
//
// 该函数将给定的折扣百分比应用于原价
// 并返回四舍五入到两位小数的最终价格。
//
// 参数:
// - price: 原价(美元)(必须为正数)
// - discountPercent: 折扣百分比 (0-100)
//
// 返回折扣后的最终价格。
//
// 如果价格为负数或折扣超过 100%,则返回错误。
//
// 示例:
//
// finalPrice, err := CalculateDiscount(100.0, 20.0)
// // finalPrice = 80.0
func CalculateDiscount(price, discountPercent float64) (float64, error) {
if price < 0 {
return 0, errors.New("price cannot be negative")
}
if discountPercent > 100 {
return 0, errors.New("discount cannot exceed 100%")
}
discountAmount := price * (discountPercent / 100)
return math.Round((price-discountAmount)*100) / 100, nil
}
openapi: 3.0.0
info:
title: 用户管理 API
version: 1.0.0
paths:
/users/{userId}:
get:
summary: 根据 ID 获取用户
description: 检索特定用户的详细信息
parameters:
- name: userId
in: path
required: true
schema:
type: integer
minimum: 1
description: 唯一的用户标识符
responses:
'200':
description: 成功找到用户
content:
application/json:
schema:
$ref: '#/components/schemas/User'
example:
id: 123
name: "John Doe"
email: "john@example.com"
'404':
description: 用户未找到
'401':
description: 未授权 - 需要身份验证
"""
表示系统中的用户
"""
type User {
"""用户的唯一标识符"""
id: ID!
"""用户的全名"""
name: String!
"""用户的电子邮件地址(已验证)"""
email: String!
"""用户的帖子(分页)"""
posts(limit: Int = 10, offset: Int = 0): [Post!]!
}
"""
根据 ID 查询特定用户
"""
type Query {
"""
通过唯一标识符获取用户
如果用户未找到则返回 null
"""
user(id: ID!): User
}
class UserManager:
"""
管理用户账户和身份验证。
该类为包括创建、身份验证和配置文件更新在内的用户管理操作
提供了高级接口。
Attributes:
db: 数据库连接实例
cache: 用于会话管理的 Redis 缓存
Example:
>>> manager = UserManager(db=get_db(), cache=get_cache())
>>> user = manager.create_user("john@example.com", "password")
>>> authenticated = manager.authenticate("john@example.com", "password")
>>> authenticated is not None
True
Thread Safety:
该类是线程安全的。多个线程可以安全地并发调用方法。
Note:
所有密码在存储前都会自动使用 bcrypt 进行哈希处理。
切勿将预先哈希处理的密码传递给方法。
"""
def __init__(self, db: Database, cache: Cache):
"""
使用数据库和缓存初始化 UserManager。
Args:
db: 用于持久化存储的数据库连接
cache: 用于会话管理的 Redis 缓存
Raises:
ConnectionError: 如果无法连接到数据库或缓存
"""
self.db = db
self.cache = cache
# 项目名称
项目功能的简要描述(1-2 句话)。
## 特性
- 关键特性 1
- 关键特性 2
- 关键特性 3
## 安装
```bash
pip install project-name
from project import MainClass
# 简单用法示例
client = MainClass(api_key="your-key")
result = client.do_something()
print(result)
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
api_key | str | None | API 身份验证密钥 |
timeout | int | 30 | 请求超时时间(秒) |
查看完整的 API 文档
do_something(param1, param2)描述此方法的功能。
参数:
param1 (str): 参数 1 的描述param2 (int): 参数 2 的描述返回: 返回值的描述
示例:
result = client.do_something("value", 42)
请参阅 CONTRIBUTING.md
MIT 许可证 - 请参阅 LICENSE
## 文档反模式
### ❌ 冗余注释
```python
# 不好:显而易见的注释没有增加价值
i = i + 1 # 递增 i
# 好:注释解释了原因
i = i + 1 # 跳过标题行
# 不好:注释与代码不匹配
def get_users(limit=10): # 注释说:返回所有用户
"""返回系统中的所有用户。""" # 但限制是 10!
return User.query.limit(limit).all()
# 好:保持文档同步
def get_users(limit=10):
"""
从系统中返回最多 'limit' 个用户。
Args:
limit: 要返回的最大用户数(默认值:10)
"""
return User.query.limit(limit).all()
# 不好:记录了如何实现(实现细节)
def sort_users(users):
"""使用冒泡排序算法对用户进行排序。""" # 我们不关心这个!
...
# 好:记录了功能是什么(契约)
def sort_users(users):
"""返回按姓名字母顺序排序的用户。"""
...
cargo doc 的内置文档□ 公共 API 有文档字符串/注释
□ 参数和返回值已记录
□ 异常/错误已记录
□ 提供了使用示例
□ 记录了边界情况和限制
□ README 包含快速开始
□ API 参考可用
□ 配置选项已记录
□ 文档与代码保持同步
□ 记录了破坏性变更
每周安装次数
77
代码仓库
GitHub 星标数
18
首次出现
2026年1月23日
安全审计
安装于
opencode59
gemini-cli58
claude-code58
codex56
github-copilot56
cursor54
Best practices for documenting APIs and code interfaces. Eliminates ~100-150 lines of redundant documentation guidance per agent.
def calculate_discount(price: float, discount_percent: float) -> float:
"""
Calculate discounted price with percentage off.
Args:
price: Original price in dollars (must be positive)
discount_percent: Discount percentage (0-100)
Returns:
Final price after discount, rounded to 2 decimals
Raises:
ValueError: If price is negative or discount > 100
Examples:
>>> calculate_discount(100.0, 20.0)
80.0
>>> calculate_discount(50.0, 50.0)
25.0
Note:
Discount percent is capped at 100% (minimum price of 0)
"""
if price < 0:
raise ValueError("Price cannot be negative")
if discount_percent > 100:
raise ValueError("Discount cannot exceed 100%")
discount_amount = price * (discount_percent / 100)
return round(price - discount_amount, 2)
/**
* Calculate discounted price with percentage off
*
* @param {number} price - Original price in dollars (must be positive)
* @param {number} discountPercent - Discount percentage (0-100)
* @returns {number} Final price after discount, rounded to 2 decimals
* @throws {Error} If price is negative or discount > 100
*
* @example
* calculateDiscount(100.0, 20.0)
* // returns 80.0
*
* @example
* calculateDiscount(50.0, 50.0)
* // returns 25.0
*/
function calculateDiscount(price, discountPercent) {
if (price < 0) {
throw new Error('Price cannot be negative');
}
if (discountPercent > 100) {
throw new Error('Discount cannot exceed 100%');
}
const discountAmount = price * (discountPercent / 100);
return Math.round((price - discountAmount) * 100) / 100;
}
// CalculateDiscount calculates discounted price with percentage off.
//
// The function applies the given discount percentage to the original price
// and returns the final price rounded to 2 decimal places.
//
// Parameters:
// - price: Original price in dollars (must be positive)
// - discountPercent: Discount percentage (0-100)
//
// Returns the final price after discount.
//
// Returns an error if price is negative or discount exceeds 100%.
//
// Example:
//
// finalPrice, err := CalculateDiscount(100.0, 20.0)
// // finalPrice = 80.0
func CalculateDiscount(price, discountPercent float64) (float64, error) {
if price < 0 {
return 0, errors.New("price cannot be negative")
}
if discountPercent > 100 {
return 0, errors.New("discount cannot exceed 100%")
}
discountAmount := price * (discountPercent / 100)
return math.Round((price-discountAmount)*100) / 100, nil
}
openapi: 3.0.0
info:
title: User Management API
version: 1.0.0
paths:
/users/{userId}:
get:
summary: Get user by ID
description: Retrieves detailed information for a specific user
parameters:
- name: userId
in: path
required: true
schema:
type: integer
minimum: 1
description: Unique user identifier
responses:
'200':
description: User found successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
example:
id: 123
name: "John Doe"
email: "john@example.com"
'404':
description: User not found
'401':
description: Unauthorized - authentication required
"""
Represents a user in the system
"""
type User {
"""Unique identifier for the user"""
id: ID!
"""User's full name"""
name: String!
"""User's email address (validated)"""
email: String!
"""User's posts (paginated)"""
posts(limit: Int = 10, offset: Int = 0): [Post!]!
}
"""
Query a specific user by ID
"""
type Query {
"""
Get user by unique identifier
Returns null if user not found
"""
user(id: ID!): User
}
class UserManager:
"""
Manages user accounts and authentication.
This class provides a high-level interface for user management
operations including creation, authentication, and profile updates.
Attributes:
db: Database connection instance
cache: Redis cache for session management
Example:
>>> manager = UserManager(db=get_db(), cache=get_cache())
>>> user = manager.create_user("john@example.com", "password")
>>> authenticated = manager.authenticate("john@example.com", "password")
>>> authenticated is not None
True
Thread Safety:
This class is thread-safe. Multiple threads can safely call
methods concurrently.
Note:
All passwords are automatically hashed using bcrypt before
storage. Never pass pre-hashed passwords to methods.
"""
def __init__(self, db: Database, cache: Cache):
"""
Initialize UserManager with database and cache.
Args:
db: Database connection for persistent storage
cache: Redis cache for session management
Raises:
ConnectionError: If unable to connect to database or cache
"""
self.db = db
self.cache = cache
# Project Name
Brief description of what the project does (1-2 sentences).
## Features
- Key feature 1
- Key feature 2
- Key feature 3
## Installation
```bash
pip install project-name
from project import MainClass
# Simple usage example
client = MainClass(api_key="your-key")
result = client.do_something()
print(result)
| Option | Type | Default | Description |
|---|---|---|---|
api_key | str | None | API authentication key |
timeout | int | 30 | Request timeout in seconds |
See full API Documentation
do_something(param1, param2)Description of what this does.
Parameters:
param1 (str): Description of param1param2 (int): Description of param2Returns: Description of return value
Example:
result = client.do_something("value", 42)
See CONTRIBUTING.md
MIT License - see LICENSE
## Documentation Anti-Patterns
### ❌ Redundant Comments
```python
# Bad: Obvious comment adds no value
i = i + 1 # Increment i
# Good: Comment explains WHY
i = i + 1 # Skip header row
# Bad: Comment doesn't match code
def get_users(limit=10): # Comment says: Returns all users
"""Returns all users in the system.""" # But limit is 10!
return User.query.limit(limit).all()
# Good: Keep docs synchronized
def get_users(limit=10):
"""
Returns up to 'limit' users from the system.
Args:
limit: Maximum number of users to return (default: 10)
"""
return User.query.limit(limit).all()
# Bad: Documents HOW (implementation)
def sort_users(users):
"""Uses bubble sort algorithm to sort users.""" # Don't care!
...
# Good: Documents WHAT (contract)
def sort_users(users):
"""Returns users sorted alphabetically by name."""
...
cargo doc□ Public APIs have docstrings/comments
□ Parameters and return values documented
□ Exceptions/errors documented
□ Usage examples provided
□ Edge cases and limitations noted
□ README includes quick start
□ API reference available
□ Configuration options documented
□ Docs are up to date with code
□ Breaking changes documented
Weekly Installs
77
Repository
GitHub Stars
18
First Seen
Jan 23, 2026
Security Audits
Gen Agent Trust HubFailSocketPassSnykPass
Installed on
opencode59
gemini-cli58
claude-code58
codex56
github-copilot56
cursor54
Lark Drive API 使用指南:飞书云文档、Wiki、表格 Token 处理与文件管理
32,299 周安装
Confluence 专家指南:空间管理、文档架构、模板与协作知识库搭建
96 周安装
构建完整AI聊天应用指南:Next.js + Neon + AI SDK实现持久化聊天与自动命名
96 周安装
员工手册AI助手:快速解答公司政策、福利、流程问题,提升HR效率
96 周安装
Auth0 Nuxt SDK:Nuxt 3/4 服务端会话认证完整指南
96 周安装
Svelte 5 Runes 静态站点构建指南:避免水合错误,适配 adapter-static
96 周安装
WordPress插件主题测试与质量保证指南:PHPUnit、WP_Mock、PHPCS与CI/CD实战
96 周安装