api-documentation について
api-documentationは、開発者やコーディングエージェント向けにAPIとコードインターフェースの文書化を案内するスキルです。原則、言語別の例、API形式、よくある問題を扱います。
主な機能
- 01文書化の原則とアンチパターン
- 02Python docstring、JSDoc、Godocの例
- 03RESTとGraphQLの文書例
- 04READMEの構成とチェックリスト
- 05文書生成ツールの紹介
活用シーン
- 01公開関数やメソッドの文書作成
- 02RESTまたはGraphQL APIリファレンスの作成
- 03プロジェクトREADMEの構成
- 04古い文書や冗長なコメントの確認
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ bobmatnyc/ claude-mpm-skills --skill api-documentationインストール後、Claude Code で/api-documentationを入力して読み込まれたか確認します。
同梱ファイルmetadata.json
詳細
API ドキュメント
API とコードインターフェースをドキュメント化するためのベストプラクティスです。エージェントごとに重複していたドキュメント作成のガイダンスを約100~150行削減します。
ドキュメント作成の基本原則
- 何をするかだけでなく、なぜそうするのかを記述する - 意図と理由を説明します
- ドキュメントをコードの近くに置く - インラインのドキュメントはコードと同期した状態を保てます
- 実装ではなく、契約を記述する - 動作に焦点を当てます
- 例は欠かせません - 実際の使い方を示します
- コードと一緒にドキュメントを更新する - 古いドキュメントは、ドキュメントがないよりも悪いものです
関数/メソッドのドキュメント
Python(Docstring)
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_key | str | None | API 認証キー |
timeout | int | 30 | リクエストのタイムアウト(秒) |
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:docstring から 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 対応