api-documentation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Documentation
API文档
Best practices for documenting APIs and code interfaces. Eliminates ~100-150 lines of redundant documentation guidance per agent.
API和代码接口文档编写的最佳实践。每个Agent可减少约100-150行冗余文档指导。
Core Documentation Principles
核心文档编写原则
- Document the why, not just the what - Explain intent and rationale
- Keep docs close to code - Inline documentation stays synchronized
- Document contracts, not implementation - Focus on behavior
- Examples are essential - Show real usage
- Update docs with code - Outdated docs are worse than no docs
- 记录原因,而非仅记录内容 - 解释意图和基本原理
- 文档贴近代码 - 内联文档保持同步
- 记录契约,而非实现细节 - 聚焦行为
- 示例必不可少 - 展示实际用法
- 随代码更新文档 - 过时文档不如无文档
Function/Method Documentation
函数/方法文档
Python (Docstrings)
Python(Docstrings)
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)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)
JavaScript(JSDoc)
javascript
/**
* 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;
}javascript
/**
* 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)
Go(Godoc)
go
// 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
}go
// 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 Endpoint Documentation
API端点文档
REST API (OpenAPI/Swagger)
REST API(OpenAPI/Swagger)
yaml
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 requiredyaml
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 requiredGraphQL
GraphQL
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
}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/Module Documentation
类/模块文档
python
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 = cachepython
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 = cacheREADME Documentation Structure
README文档结构
markdown
undefinedmarkdown
undefinedProject Name
Project Name
Brief description of what the project does (1-2 sentences).
Brief description of what the project does (1-2 sentences).
Features
Features
- Key feature 1
- Key feature 2
- Key feature 3
- Key feature 1
- Key feature 2
- Key feature 3
Installation
Installation
bash
pip install project-namebash
pip install project-nameQuick Start
Quick Start
python
from project import MainClasspython
from project import MainClassSimple usage example
Simple usage example
client = MainClass(api_key="your-key")
result = client.do_something()
print(result)
undefinedclient = MainClass(api_key="your-key")
result = client.do_something()
print(result)
undefinedConfiguration
Configuration
| Option | Type | Default | Description |
|---|---|---|---|
| str | None | API authentication key |
| int | 30 | Request timeout in seconds |
| Option | Type | Default | Description |
|---|---|---|---|
| str | None | API authentication key |
| int | 30 | Request timeout in seconds |
API Reference
API Reference
See full API Documentation
See full API Documentation
Main Methods
Main Methods
do_something(param1, param2)
do_something(param1, param2)do_something(param1, param2)
do_something(param1, param2)Description of what this does.
Parameters:
- (str): Description of param1
param1 - (int): Description of param2
param2
Returns: Description of return value
Example:
python
result = client.do_something("value", 42)Description of what this does.
Parameters:
- (str): Description of param1
param1 - (int): Description of param2
param2
Returns: Description of return value
Example:
python
result = client.do_something("value", 42)Contributing
Contributing
See CONTRIBUTING.md
See CONTRIBUTING.md
License
License
MIT License - see LICENSE
undefinedMIT License - see LICENSE
undefinedDocumentation Anti-Patterns
文档反模式
❌ Redundant Comments
❌ 冗余注释
python
undefinedpython
undefinedBad: Obvious comment adds no value
糟糕:显而易见的注释没有价值
i = i + 1 # Increment i
i = i + 1 # 递增i
Good: Comment explains WHY
良好:注释解释原因
i = i + 1 # Skip header row
undefinedi = i + 1 # 跳过标题行
undefined❌ Outdated Documentation
❌ 过时文档
python
undefinedpython
undefinedBad: 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()
def get_users(limit=10): # 注释说:返回所有用户
"""Returns all users in the system.""" # 但限制是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()undefineddef 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()undefined❌ Implementation Documentation
❌ 实现细节文档
python
undefinedpython
undefinedBad: Documents HOW (implementation)
糟糕:记录实现方式
def sort_users(users):
"""Uses bubble sort algorithm to sort users.""" # Don't care!
...
def sort_users(users):
"""使用冒泡排序算法对用户进行排序。""" # 我们不关心这个!
...
Good: Documents WHAT (contract)
良好:记录功能契约
def sort_users(users):
"""Returns users sorted alphabetically by name."""
...
undefineddef sort_users(users):
"""返回按名称字母顺序排序的用户列表。"""
...
undefinedDocumentation Tools
文档工具
Python
Python
- Sphinx: Generate HTML docs from docstrings
- pdoc: Simpler alternative to Sphinx
- MkDocs: Markdown-based documentation
- Sphinx: 从docstring生成HTML文档
- pdoc: Sphinx的简易替代工具
- MkDocs: 基于Markdown的文档工具
JavaScript
JavaScript
- JSDoc: Generate HTML from JSDoc comments
- TypeDoc: For TypeScript projects
- Docusaurus: Full documentation websites
- JSDoc: 从JSDoc注释生成HTML文档
- TypeDoc: 适用于TypeScript项目
- Docusaurus: 完整的文档网站搭建工具
Go
Go
- godoc: Built-in documentation tool
- pkgsite: Go package documentation
- godoc: 内置文档工具
- pkgsite: Go包文档平台
Rust
Rust
- rustdoc: Built-in documentation with
cargo doc
- rustdoc: 内置文档工具,通过生成
cargo doc
Quick Documentation Checklist
快速文档检查清单
□ 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□ 公共API包含docstring/注释
□ 参数和返回值已记录
□ 异常/错误已记录
□ 提供使用示例
□ 注明边缘情况和限制
□ README包含快速入门
□ 提供API参考
□ 配置选项已记录
□ 文档与代码保持同步
□ 破坏性变更已记录Remember
谨记
- Code is read more than written - Good docs save time
- Examples speak louder than descriptions - Show, don't just tell
- The best docs are no docs - Write self-documenting code
- Keep it DRY - Don't repeat what the code already says
- Update docs with code - Outdated docs mislead developers
- 代码阅读次数远超编写次数 - 优质文档节省时间
- 示例比描述更有说服力 - 展示,而非仅说明
- 最佳文档是无需文档 - 编写自解释代码
- 保持DRY原则 - 不要重复代码已表达的内容
- 随代码更新文档 - 过时文档会误导开发者