Documentation is the bridge between brilliant code and the developers who need to understand, maintain, and extend it. Claude Code transforms documentation from a dreaded chore into an automated process that keeps pace with your rapidly evolving codebase. This lesson explores how to generate everything from API references to architectural diagrams.
Scenario: Your startup just hit product-market fit. The codebase grew 10x in six months. New developers join weekly. The wiki is three sprints behind reality. Customer support can’t explain new features because docs don’t exist. Sound familiar? Here’s how Claude Code solves this.
Week 1: Plan documentation sprint
- Assign writers to each module
- Review existing (outdated) docs
- Interview developers for context
Week 2-3: Write documentation
- Create diagrams by hand
Week 4: Reviews and updates
- Technical review by developers
- Update for recent changes
Result: Outdated before it's published
Day 1: Automated generation
> Generate complete API documentation for our service
> Include examples, types, and error responses
> Create architecture documentation with diagrams
> Focus on data flow and service interactions
> Write user guides for each feature
> Target both developers and end users
- AI-generated drafts ready
- Developers review for accuracy
- Continuous updates with code
Result: Always current, comprehensive docs
Set up documentation templates
Create .claude/commands/generate-docs.md
:
Generate documentation for: $ARGUMENTS
1. Analyze code structure and patterns
2. Generate appropriate documentation:
- JSDoc/TSDoc for functions
- Architecture overview for systems
- User guides for features
4. Add diagrams where helpful
5. Follow our style guide
Configure documentation preferences
In .claude/settings.json
:
"diagramTool" : " mermaid " ,
"languages" : [ " en " , " es " , " zh " ]
Create style guide
> Create a documentation style guide that includes:
> - Tone and voice (professional but approachable)
Set up auto-generation hooks
> Create a git hook that reminds to update docs:
> - On feature branch merge
> - When API endpoints change
> - After major refactoring
> Generate comprehensive API documentation for our REST endpoints.
> - Endpoint URLs and methods
> - Request/response schemas
> - Authentication requirements
> - Rate limiting details
> - Example requests and responses
> - Error codes and meanings
Claude generates structured documentation:
Endpoint Overview
All endpoints require Bearer token authentication:
Authorization: Bearer <token>
- 1000 requests per hour per user
- 429 status when exceeded
- X-RateLimit-Remaining header
Production: https://api.example.com/v2
Staging: https://staging-api.example.com/v2
Endpoint Details
Retrieve a single user by ID.
| Name | Type | In | Description |
|------|------|-----|-------------|
| id | string | path | User UUID |
| include | string | query | Comma-separated related data |
"id" : " 123e4567-e89b-12d3-a456-426614174000 " ,
"email" : " user@example.com " ,
"created_at" : " 2024-01-15T09:30:00Z " ,
"avatar_url" : " https://... " ,
"bio" : " Software developer "
"error" : " USER_NOT_FOUND " ,
"message" : " User with specified ID not found "
<Card title="Code Examples">
const response = await fetch('https://api.example.com/v2/users/123', {
'Authorization': 'Bearer your-token-here'
const user = await response.json();
'https://api.example.com/v2/users/123',
headers={'Authorization': 'Bearer your-token-here'}
curl -X GET https://api.example.com/v2/users/123 \
-H "Authorization: Bearer your-token-here"
OpenAPI Spec
$ref : ' #/components/schemas/User '
> Generate GraphQL schema documentation with:
> - Query and mutation examples
> - Subscription patterns
> - Performance considerations
Result:
User type representing an authenticated user in the system
"""User's email address"""
"""User's posts with pagination"""
"""Number of posts to return"""
"""Cursor for pagination"""
"""User's account creation date"""
"""Get current authenticated user"""
"""Search users by name or email"""
searchUsers ( query : String ! ): [ User ! ] !
> Analyze our codebase and create comprehensive architecture documentation:
> - System overview and components
> - Technology stack details
> - Deployment architecture
Claude generates:
Our platform follows a microservices architecture with the following core components:
- ** Technology ** : Next.js 14 with TypeScript
- ** State Management ** : Zustand + React Query
- ** UI Framework ** : Tailwind CSS + Radix UI
1. ** API Gateway ** (Node.js/Express)
2. ** User Service ** (Node.js)
- Authentication/Authorization
3. ** Product Service ** (Python/FastAPI)
4. ** Order Service ** (Go)
- ** Primary Database ** : PostgreSQL 15
- ** Search ** : Elasticsearch 8
- ** Message Queue ** : RabbitMQ
graph TB
subgraph "Client Layer"
Web[Web App]
Mobile[Mobile App]
end
subgraph "API Layer"
Gateway[API Gateway]
Auth[Auth Service]
end
subgraph "Service Layer"
User[User Service]
Product[Product Service]
Order[Order Service]
Notification[Notification Service]
end
subgraph "Data Layer"
PG[(PostgreSQL)]
Redis[(Redis)]
ES[(Elasticsearch)]
MQ[RabbitMQ]
end
Web --> Gateway
Mobile --> Gateway
Gateway --> Auth
Auth --> User
Gateway --> Product
Gateway --> Order
Order --> MQ
MQ --> Notification
User --> PG
Product --> PG
Product --> ES
Order --> PG
Gateway --> Redis
# Kubernetes Deployment Architecture
## Production Cluster (AWS EKS)
- Region : us-east-1 (primary), us-west-2 (failover)
- General : t3.large (3-10 nodes)
- Compute : c5.xlarge (2-5 nodes)
- Memory : r5.large (2-4 nodes)
- API Gateway : 3 replicas, HPA (CPU 70%)
- User Service : 2 replicas, HPA (CPU 60%)
- Product Service : 3 replicas, HPA (Memory 70%)
- Order Service : 2 replicas, HPA (CPU 50%)
- Load Balancer : AWS ALB with WAF
- Database : RDS Multi-AZ PostgreSQL
- Cache : ElastiCache Redis cluster
> Document the authentication module:
> - Purpose and responsibilities
> - Internal architecture
> - Security considerations
Generated documentation:
The authentication module provides secure user authentication and authorization for the entire application. It implements JWT-based authentication with refresh tokens and supports multiple authentication providers.
- JWT token generation and validation
- OAuth2 integration (Google, GitHub, Microsoft)
- Role-based access control (RBAC)
- Multi-factor authentication (MFA)
Main service class handling authentication logic.
* Authenticate user with email and password
* @returns JWT access token and refresh token
async login ( email : string , password : string ) : Promise < AuthTokens >
* Validate and refresh access token
async refreshToken ( refreshToken : string ) : Promise < AuthTokens >
* Revoke all user sessions
async logout ( userId : string ) : Promise < void >
Handles JWT token operations.
Secure password hashing and validation.
Abstract class for OAuth integrations.
Password Storage : Bcrypt with cost factor 12
Token Security :
Access tokens: 15 minutes TTL
Refresh tokens: 7 days TTL, single use
Tokens signed with RS256
Rate Limiting : 5 login attempts per 15 minutes
Session Security : Secure, httpOnly, sameSite cookies
### Inline Documentation Generation
Add comprehensive JSDoc comments to our utility functions:
Describe purpose
Document parameters and returns
Include usage examples
Note any side effects
function calculateDiscount(price, discountPercent, maxDiscount) {
const discount = price * (discountPercent / 100);
return Math.min(discount, maxDiscount || Infinity);
After:
* Calculates the discount amount for a given price and discount percentage
* @param {number} price - The original price in cents
* @param {number} discountPercent - The discount percentage (0-100)
* @param {number} [maxDiscount] - Optional maximum discount amount in cents
* @returns {number} The calculated discount amount in cents, capped at maxDiscount if provided
* // 20% discount on $100
* calculateDiscount(10000, 20) // returns 2000
* // 50% discount on $100, capped at $30
* calculateDiscount(10000, 50, 3000) // returns 3000
function calculateDiscount ( price , discountPercent , maxDiscount ) {
const discount = price * ( discountPercent / 100 );
return Math . min ( discount , maxDiscount || Infinity );
> Generate TypeScript type documentation for our data models
* Represents a user in the system
/** Unique identifier for the user */
/** User's email address - must be unique */
/** User's display name */
/** User's role determining access permissions */
role : ' admin ' | ' user ' | ' guest ' ;
/** Account creation timestamp */
/** Last update timestamp */
/** Optional user profile information */
* Extended user profile information
export interface UserProfile {
/** URL to user's avatar image */
/** User's biography or description */
/** Social media links */
> Create a sequence diagram for our order processing flow
sequenceDiagram
participant U as User
participant F as Frontend
participant G as API Gateway
participant O as Order Service
participant P as Payment Service
participant I as Inventory Service
participant N as Notification Service
U->>F: Submit order
F->>G: POST /orders
G->>G: Validate auth token
G->>O: Create order
O->>I: Check inventory
I-->>O: Inventory available
O->>P: Process payment
P-->>O: Payment successful
O->>I: Reserve inventory
O->>N: Send confirmation
O-->>G: Order created
G-->>F: Order response
F-->>U: Show confirmation
Note over N,U: Async email sent
N-->>U: Email confirmation
> Generate an ER diagram for our user and order tables
erDiagram
USER ||--o{ ORDER : places
USER ||--o{ ADDRESS : has
ORDER ||--|{ ORDER_ITEM : contains
PRODUCT ||--o{ ORDER_ITEM : "ordered in"
USER {
uuid id PK
string email UK
string name
string password_hash
timestamp created_at
}
ADDRESS {
uuid id PK
uuid user_id FK
string street
string city
string country
string postal_code
}
ORDER {
uuid id PK
uuid user_id FK
string status
decimal total
timestamp created_at
}
ORDER_ITEM {
uuid id PK
uuid order_id FK
uuid product_id FK
integer quantity
decimal price
}
PRODUCT {
uuid id PK
string name
string sku UK
decimal price
integer stock
}
> Create user documentation for our shopping cart feature:
> - Step-by-step instructions
> - Screenshots placeholders
Generated guide:
The shopping cart allows you to collect items before checkout, save them for later, and manage quantities.
- Click the "Add to Cart" button
- Select quantity (optional)
- Choose product options (size, color, etc.)
![ Product page add to cart ] ( screenshots/add-to-cart.png )
- Hover over product in catalog
- Item added with default options
#### Viewing Cart Contents
- Click cart icon in header
- Click "View Full Cart" for details
2. Use +/- buttons or enter number
3. Changes save automatically
- Confirm removal in popup
1. Click "Save for Later"
2. Item moves to wishlist
3. Access from account menu
** Cart is empty after login **
- Solution: Cart items are saved for 30 days
- Check if browsing as guest previously
** Can't update quantity **
- Issue: Limited stock available
- Solution: Check product availability
- Items show current prices
- Original price shown strikethrough
> Create an integration guide for developers using our API
Get up and running with our API in 5 minutes.
curl -X POST https://api.example.com/v2/auth/api-keys \
-H "Content-Type: application/json" \
-d ' {"email": "you@example.com", "password": "your-password"} '
const API_KEY = ' your-api-key ' ;
const API_URL = ' https://api.example.com/v2 ' ;
fetch ( ` ${ API_URL } /products ` , {
' Authorization ' : ` Bearer ${ API_KEY } `
. then ( products => console . log ( products ));
All responses follow this format:
"data" : { /* requested data */ },
"timestamp" : " 2024-01-15T10:00:00Z "
Best for server-to-server communication.
Best for user-facing applications.
Detailed OAuth flow →
// Get page 2 with 50 items per page
fetch ( ` ${ API_URL } /products?page=2&limit=50 ` )
// Filter products by category and price
fetch ( ` ${ API_URL } /products?category=electronics&max_price=500 ` )
Register webhooks for real-time updates:
fetch ( ` ${ API_URL } /webhooks ` , {
' Authorization ' : ` Bearer ${ API_KEY } ` ,
' Content-Type ' : ' application/json '
url: ' https://your-app.com/webhook ' ,
events: [ ' order.created ' , ' order.updated ' ]
## Documentation Maintenance
Create a documentation update workflow:
Git hooks for doc reminders
Automated freshness checks
Version tracking
Deprecation notices
# Check if API files changed
if git diff --cached --name-only | grep -q "api/"; then
echo "⚠️ API files changed. Remember to update docs!"
echo "Run: claude /generate-api-docs"
Documentation Freshness Check
class DocFreshnessChecker {
const docs = await this . loadDocs ();
const code = await this . loadCode ();
for ( const doc of docs) {
const codeFile = this . findRelatedCode (doc);
if (codeFile . lastModified > doc . lastModified ) {
console . warn ( ` 📚 ${ doc . path } may be outdated ` );
Version Tracking
code_version : commit:abc123
> ⚠️ This documentation is for v2.3.0.
> See [ version history ] ( ./versions ) for other versions.
Deprecation Workflow
* @deprecated Since v2.1.0. Use `newMethod` instead.
* Will be removed in v3.0.0.
console . warn ( ' oldMethod is deprecated. Use newMethod instead. ' );
> Generate documentation in multiple languages:
> - Include cultural adaptations
Claude generates localized versions:
Welcome to our API! This guide will help you integrate quickly.
¡Bienvenido a nuestra API! Esta guía te ayudará a integrar rápidamente.
<!-- Simplified Chinese -->
> 1. Write the documentation first
> 2. Get stakeholder approval
> 3. Implement to match docs
> 4. Update docs with learnings
> Set up continuous documentation:
> - Auto-generate from code comments
> - Update with each deployment
> - Include in CI/CD pipeline
> - Monitor documentation coverage
> Every API endpoint should have:
> - Complete request example
> - Success response example
> - Error response examples
> Create interactive API documentation:
> - Embedded API playground
> - Copy-paste ready snippets
> - Response visualization
Track documentation quality:
> Create a documentation dashboard showing:
> - Coverage (% of code documented)
> - Freshness (days since update)
> - Completeness (required sections)
> - Usage (page views, time on page)
> - Feedback (helpfulness ratings)
You’ve learned how to transform Claude Code into a documentation powerhouse. The key is treating documentation as code - automated, version-controlled, and continuously updated. No more outdated wikis or missing API docs.
Remember: The best documentation is the one that exists and stays current. Use Claude Code to lower the barrier to documentation creation so dramatically that keeping docs updated becomes trivial. Your future self (and your teammates) will thank you.