Skip to content

Documentation Generation

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
- Manually inspect code
- Create diagrams by hand
- Write API examples
- Hope nothing changes
Week 4: Reviews and updates
- Technical review by developers
- Fix inaccuracies
- Update for recent changes
- Publish to wiki
Result: Outdated before it's published
  1. Set up documentation templates Create .claude/commands/generate-docs.md:

    Generate documentation for: $ARGUMENTS
    1. Analyze code structure and patterns
    2. Generate appropriate documentation:
    - API docs for endpoints
    - JSDoc/TSDoc for functions
    - Architecture overview for systems
    - User guides for features
    3. Include code examples
    4. Add diagrams where helpful
    5. Follow our style guide
  2. Configure documentation preferences In .claude/settings.json:

    {
    "documentation": {
    "apiFormat": "openapi",
    "diagramTool": "mermaid",
    "codeExamples": true,
    "versionTracking": true,
    "languages": ["en", "es", "zh"]
    }
    }
  3. Create style guide

    > Create a documentation style guide that includes:
    > - Tone and voice (professional but approachable)
    > - Formatting standards
    > - Example templates
    > - Terminology glossary
  4. 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.
> Include:
> - 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

# User API
## Authentication
All endpoints require Bearer token authentication:

Authorization: Bearer <token>

## Rate Limiting
- 1000 requests per hour per user
- 429 status when exceeded
- X-RateLimit-Remaining header
## Base URL
Production: https://api.example.com/v2
Staging: https://staging-api.example.com/v2

Endpoint Details

## GET /users/{id}
Retrieve a single user by ID.
### Parameters
| Name | Type | In | Description |
|------|------|-----|-------------|
| id | string | path | User UUID |
| include | string | query | Comma-separated related data |
### Response 200
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com",
"name": "John Doe",
"created_at": "2024-01-15T09:30:00Z",
"profile": {
"avatar_url": "https://...",
"bio": "Software developer"
}
}
{
"error": "USER_NOT_FOUND",
"message": "User with specified ID not found"
}
JavaScript/Node.js
</Card>
<Card title="Code Examples">
```javascript
const response = await fetch('https://api.example.com/v2/users/123', {
headers: {
'Authorization': 'Bearer your-token-here'
}
});
const user = await response.json();
// Python
import requests
response = requests.get(
'https://api.example.com/v2/users/123',
headers={'Authorization': 'Bearer your-token-here'}
)
user = response.json()
// cURL
curl -X GET https://api.example.com/v2/users/123 \
-H "Authorization: Bearer your-token-here"

OpenAPI Spec

openapi: 3.0.0
info:
title: User API
version: 2.0.0
paths:
/users/{id}:
get:
summary: Get user by ID
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
responses:
'200':
description: User found
content:
application/json:
schema:
$ref: '#/components/schemas/User'
> Generate GraphQL schema documentation with:
> - Type definitions
> - Query and mutation examples
> - Subscription patterns
> - Error handling
> - Performance considerations

Result:

"""
User type representing an authenticated user in the system
"""
type User {
"""Unique identifier"""
id: ID!
"""User's email address"""
email: String!
"""Display name"""
name: String!
"""User's posts with pagination"""
posts(
"""Number of posts to return"""
first: Int = 10
"""Cursor for pagination"""
after: String
): PostConnection!
"""User's account creation date"""
createdAt: DateTime!
}
"""
Root query type
"""
type Query {
"""Get current authenticated user"""
me: User
"""Find user by ID"""
user(id: ID!): User
"""Search users by name or email"""
searchUsers(query: String!): [User!]!
}
> Analyze our codebase and create comprehensive architecture documentation:
> - System overview and components
> - Data flow diagrams
> - Service interactions
> - Technology stack details
> - Deployment architecture

Claude generates:

# System Architecture
## Overview
Our platform follows a microservices architecture with the following core components:
### Frontend
- **Technology**: Next.js 14 with TypeScript
- **Hosting**: Vercel
- **State Management**: Zustand + React Query
- **UI Framework**: Tailwind CSS + Radix UI
### Backend Services
1. **API Gateway** (Node.js/Express)
- Request routing
- Authentication
- Rate limiting
2. **User Service** (Node.js)
- User management
- Authentication/Authorization
- Profile management
3. **Product Service** (Python/FastAPI)
- Product catalog
- Inventory management
- Search functionality
4. **Order Service** (Go)
- Order processing
- Payment integration
- Order tracking
### Data Layer
- **Primary Database**: PostgreSQL 15
- **Cache**: Redis 7
- **Search**: Elasticsearch 8
- **Message Queue**: RabbitMQ
> Document the authentication module:
> - Purpose and responsibilities
> - Public API
> - Internal architecture
> - Security considerations
> - Usage examples

Generated documentation:

# Authentication Module
## Overview
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.
## Features
- JWT token generation and validation
- Refresh token rotation
- OAuth2 integration (Google, GitHub, Microsoft)
- Role-based access control (RBAC)
- Session management
- Multi-factor authentication (MFA)
## Architecture
### Components
#### AuthService
Main service class handling authentication logic.
```typescript
class AuthService {
/**
* 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.

  1. Password Storage: Bcrypt with cost factor 12
  2. Token Security:
    • Access tokens: 15 minutes TTL
    • Refresh tokens: 7 days TTL, single use
    • Tokens signed with RS256
  3. Rate Limiting: 5 login attempts per 15 minutes
  4. Session Security: Secure, httpOnly, sameSite cookies
## Code Documentation
### Inline Documentation Generation

Add comprehensive JSDoc comments to our utility functions:

  • Describe purpose
  • Document parameters and returns
  • Include usage examples
  • Note any side effects
Before:
```javascript
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
*
* @example
* // 20% discount on $100
* calculateDiscount(10000, 20) // returns 2000
*
* @example
* // 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
* @interface User
*/
export interface User {
/** Unique identifier for the user */
id: string;
/** User's email address - must be unique */
email: string;
/** User's display name */
name: string;
/** User's role determining access permissions */
role: 'admin' | 'user' | 'guest';
/** Account creation timestamp */
createdAt: Date;
/** Last update timestamp */
updatedAt: Date;
/** Optional user profile information */
profile?: UserProfile;
}
/**
* Extended user profile information
* @interface UserProfile
*/
export interface UserProfile {
/** URL to user's avatar image */
avatarUrl?: string;
/** User's biography or description */
bio?: string;
/** User's location */
location?: string;
/** Social media links */
socialLinks?: {
twitter?: string;
github?: string;
linkedin?: string;
};
}
> 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:
> - Getting started
> - Step-by-step instructions
> - Screenshots placeholders
> - Troubleshooting
> - FAQs

Generated guide:

# Shopping Cart Guide
## Getting Started
The shopping cart allows you to collect items before checkout, save them for later, and manage quantities.
### Adding Items to Cart
1. **From Product Page**
- Click the "Add to Cart" button
- Select quantity (optional)
- Choose product options (size, color, etc.)
- Confirm addition
![Product page add to cart](screenshots/add-to-cart.png)
2. **Quick Add**
- Hover over product in catalog
- Click the cart icon
- Item added with default options
### Managing Your Cart
#### Viewing Cart Contents
- Click cart icon in header
- See mini-cart dropdown
- Click "View Full Cart" for details
#### Updating Quantities
1. Navigate to cart page
2. Use +/- buttons or enter number
3. Changes save automatically
#### Removing Items
- Click "Remove" link
- Or set quantity to 0
- Confirm removal in popup
### Saving for Later
Move items to wishlist:
1. Click "Save for Later"
2. Item moves to wishlist
3. Access from account menu
### Common Issues
**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
**Prices changed**
- Items show current prices
- Sales may have ended
- Original price shown strikethrough
> Create an integration guide for developers using our API
# API Integration Guide
## Quick Start
Get up and running with our API in 5 minutes.
### 1. Get Your API Key
```bash
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';
// List products
fetch(`${API_URL}/products`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
})
.then(res => res.json())
.then(products => console.log(products));

All responses follow this format:

{
"data": { /* requested data */ },
"meta": {
"request_id": "req_123",
"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`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://your-app.com/webhook',
events: ['order.created', 'order.updated']
})
})
## Documentation Maintenance
### Keeping Docs Current

Create a documentation update workflow:

  • Git hooks for doc reminders
  • Automated freshness checks
  • Version tracking
  • Deprecation notices
Result:
1. **Pre-commit Hook**
```bash
#!/bin/bash
# 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"
fi
  1. Documentation Freshness Check

    class DocFreshnessChecker {
    async checkFreshness() {
    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`);
    }
    }
    }
    }
  2. Version Tracking

    ---
    version: 2.3.0
    last_updated: 2024-01-15
    code_version: commit:abc123
    ---
    # API Documentation
    > ⚠️ This documentation is for v2.3.0.
    > See [version history](./versions) for other versions.
  3. Deprecation Workflow

    /**
    * @deprecated Since v2.1.0. Use `newMethod` instead.
    * Will be removed in v3.0.0.
    */
    function oldMethod() {
    console.warn('oldMethod is deprecated. Use newMethod instead.');
    return newMethod();
    }
> Generate documentation in multiple languages:
> - English (primary)
> - Spanish
> - Mandarin
> - Include cultural adaptations

Claude generates localized versions:

<!-- English -->
# Getting Started
Welcome to our API! This guide will help you integrate quickly.
<!-- Spanish -->
# Comenzando
¡Bienvenido a nuestra API! Esta guía te ayudará a integrar rápidamente.
<!-- Simplified Chinese -->
# 快速入门
欢迎使用我们的API!本指南将帮助您快速集成。
> For new features:
> 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:
> - Purpose explanation
> - Complete request example
> - Success response example
> - Error response examples
> - Common use cases
> - Edge cases
> Create interactive API documentation:
> - Embedded API playground
> - Live code examples
> - 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.