mcpField
A
api-documentation

api-documentation

github.com/bobmatnyc开发78383 次安装15 周前更新
代码仓库

关于 api-documentation

api-documentation 是面向开发者和编码 Agent 的文档编写指南,涵盖 API 与代码接口。内容包括文档原则、各语言示例、API 格式和常见问题。

主要功能

  1. 01文档原则与反模式
  2. 02Python docstring、JSDoc 和 Godoc 示例
  3. 03REST 与 GraphQL 文档示例
  4. 04README 结构与文档检查清单
  5. 05文档生成工具参考

适用场景

  1. 01为公开函数和方法编写文档
  2. 02撰写 REST 或 GraphQL API 参考
  3. 03规划项目 README 结构
  4. 04检查文档过时或注释冗余

安装

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

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill api-documentation

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

附带文件metadata.json

详细介绍

API 文档

有关 API 和代码接口文档编写的最佳实践。可为每个 Agent 减少约 100–150 行冗余的文档编写指南。

核心文档原则

  1. 说明原因,而不只是说明内容——解释意图和理由
  2. 让文档贴近代码——内联文档能保持同步
  3. 记录契约,而非实现——聚焦行为
  4. 示例必不可少——展示真实用法
  5. 随代码更新文档——过时的文档比没有文档更糟

函数/方法文档

Python(文档字符串)
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)
JavaScript(JSDoc)
/**
 * 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;
}
Go(Godoc)
// 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
}

API 端点文档

REST API(OpenAPI/Swagger)
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: "[email protected]"
        '404':
          description: User not found
        '401':
          description: Unauthorized - authentication required
GraphQL
"""
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("[email protected]", "password")
        >>> authenticated = manager.authenticate("[email protected]", "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

README 文档结构

# 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)

配置

选项类型默认值说明
api_keystrNoneAPI 身份验证密钥
timeoutint30请求超时时间,单位为秒

API 参考

参阅完整的 API 文档

主要方法
do_something(param1, param2)

说明此方法的功能。

参数:

  • param1(str):param1 的说明
  • param2(int):param2 的说明

**返回值:**返回值说明

示例:

result = client.do_something("value", 42)

贡献

参阅 CONTRIBUTING.md

许可证

MIT 许可证——参阅 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."""
    ...

文档工具

Python
  • Sphinx:根据文档字符串生成 HTML 文档
  • pdoc:比 Sphinx 更简单的替代工具
  • MkDocs:基于 Markdown 的文档工具
JavaScript
  • JSDoc:根据 JSDoc 注释生成 HTML
  • TypeDoc:适用于 TypeScript 项目
  • Docusaurus:完整的文档网站
Go
  • godoc:内置文档工具
  • pkgsite:Go 包文档
Rust
  • rustdoc:内置文档工具,使用 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

请记住

  • 阅读代码的时间多于编写代码——好的文档能节省时间
  • 示例胜过描述——展示,而不只是讲述
  • 最好的文档就是没有文档——编写自解释的代码
  • 保持 DRY——不要重复代码已经说明的内容
  • 随代码更新文档——过时的文档会误导开发者

评论

支持 Markdown