Tutorials10 min read

How to Use Claude for Code Documentation: Generate READMEs, Comments, and API Docs

Step-by-step guide to using Claude AI for code documentation — auto-generate READMEs, inline comments, JSDoc, OpenAPI specs, and changelog entries. Save hours every sprint.

How to Use Claude for Code Documentation: The Developer's Complete Guide

Most developers hate writing documentation. It's not that they don't see the value — it's that by the time a feature ships, the mental energy to explain it clearly has evaporated. The result is READMEs that stop at "Installation", inline comments that say // fix this later, and API docs that are six sprints out of date.

Claude changes this calculus entirely. With the right prompts, you can generate production-quality documentation in seconds — not as a first draft to throw away, but as something you'd actually commit.

This guide walks through seven high-value documentation tasks, with exact prompts you can use today.


Why Claude Outperforms Generic AI Tools for Documentation

Claude was trained with a specific emphasis on following instructions precisely and maintaining context across long conversations. For documentation, this matters in three ways:

Context retention. You can paste an entire module, explain your team's conventions once, and Claude will apply them consistently throughout the session — without you repeating yourself. Structured output. Claude follows markdown, JSDoc, OpenAPI, and other documentation formats with high fidelity. It doesn't hallucinate pseudo-formats. Technical accuracy. Claude understands code semantics, not just syntax. It can infer what a function does from the implementation, not just from the name.

A 2025 developer productivity study by GitClear found that developers spend an average of 4.2 hours per week on documentation tasks. Even cutting that in half compounds to 100+ hours per year per developer.


Task 1: Generate a Complete README From Scratch

A good README answers five questions: what is this, why does it exist, how do I install it, how do I use it, and how do I contribute. Claude can infer all five from your codebase.

Prompt:

Here is the entry point of my project and its package.json.

[paste your main file + package.json]

Write a complete README.md following this structure:
1. Project name and one-line description
2. Why this exists (problem it solves)
3. Prerequisites
4. Installation (exact commands)
5. Quick start with a working code example
6. Configuration options (table format)
7. Contributing guidelines
8. License

Use GitHub-flavored markdown. The audience is mid-level developers who will fork this for their own use.

What to customize: Swap "mid-level developers" for your actual audience (e.g., "backend engineers on enterprise teams" or "students learning React"). Pro tip: Run this prompt with your entire src/ directory content when using Claude with a large context window. Claude will discover undocumented features and include them automatically.

Task 2: Write Inline Comments for Legacy Code

You've inherited a 300-line function with no comments, written by someone who left the company. Here's how to handle it:

Prompt:

Here is a function written by a previous developer. Add inline comments that explain:
- What each block of logic is doing
- Why non-obvious decisions were made (infer from context)
- Any edge cases being handled
- TODOs for anything that looks risky

Keep comments concise — one line max unless the logic genuinely requires explanation. Do NOT add comments for self-evident code.

[paste function]

The key constraint is "do NOT add comments for self-evident code." Without it, Claude adds noise like // increment counter above i++. With it, you get comments that actually help the next developer.

Example output (for a rate limiter function):

typescript// Use sliding window instead of fixed window to prevent burst attacks at window boundaries
const windowStart = Date.now() - WINDOW_MS;

// Filter requests within the current window — O(n) but n is capped by MAX_REQUESTS
const recentRequests = requestLog.filter(ts => ts > windowStart);

// TODO: Move this to Redis for multi-instance deployments — in-memory won't work in production clusters
if (recentRequests.length >= MAX_REQUESTS) {
  throw new RateLimitError(`Limit of ${MAX_REQUESTS} requests per ${WINDOW_MS}ms exceeded`);
}


Task 3: Generate JSDoc / TSDoc Annotations

TypeScript's type system handles types, but it can't document intent, side effects, or expected input ranges. JSDoc fills that gap, and Claude generates it accurately.

Prompt:

Add complete JSDoc annotations to each function below. Include:
- @description — what the function does, not how
- @param — for each parameter, including constraints (e.g., "must be positive", "ISO 8601 format")
- @returns — what the return value represents
- @throws — any errors thrown and under what conditions
- @example — one working usage example

[paste your TypeScript file]

Sample output:

typescript/**
 * Calculates compound interest over a given period.
 *
 * @description Applies the standard compound interest formula (A = P(1 + r/n)^nt).
 * Rounds to 2 decimal places to avoid floating point drift in financial contexts.
 *
 * @param principal - Initial investment amount in USD. Must be positive.
 * @param annualRate - Annual interest rate as a decimal (e.g., 0.05 for 5%). Must be between 0 and 1.
 * @param years - Investment duration in years. Must be a positive integer.
 * @param compoundingsPerYear - Number of times interest compounds annually. Defaults to 12 (monthly).
 * @returns Final value after interest, rounded to 2 decimal places.
 * @throws {RangeError} If principal or years is negative, or if annualRate is outside [0, 1].
 *
 * @example
 * compoundInterest(10000, 0.07, 10) // Returns 19671.51
 */
function compoundInterest(
  principal: number,
  annualRate: number,
  years: number,
  compoundingsPerYear = 12
): number { ... }


Task 4: Generate OpenAPI / Swagger Specs From Route Handlers

If you're using Express, Fastify, Hono, or similar frameworks, Claude can read your route handlers and generate an OpenAPI 3.0 spec — the kind that powers Swagger UI and client SDK generation.

Prompt:

Here are my Express route handlers for the /users resource.

[paste routes]

Generate a complete OpenAPI 3.0 YAML spec for these routes. Include:
- Path parameters and query string params with types and validation rules
- Request body schema (infer from the handler logic)
- Response schemas for success and error cases (400, 401, 404, 500)
- Security scheme (Bearer token, inferred from the auth middleware)
- Example request and response values

When to use this: Before a new API goes to QA, paste all route files and let Claude generate the full spec in one pass. Feed the YAML to Swagger UI or Redoc for instant interactive documentation.

Task 5: Write a CHANGELOG Entry

CHANGELOG entries are consistently underwritten. "Fixed bug" tells the next developer nothing. Claude can write conventional commit-style changelog entries from a git diff.

Prompt:

Here is a git diff for a sprint's worth of changes.

[paste git diff or list of commit messages]

Write a CHANGELOG.md entry following the Keep a Changelog format:
- Version and date at the top
- Group changes under: Added, Changed, Fixed, Deprecated, Removed, Security
- Each entry should explain the user/developer impact, not just what changed
- Flag anything that is a breaking change with [BREAKING]

Shortcut: Run git diff main..feature-branch and paste the output directly. For large diffs, use git log --oneline main..feature-branch for a cleaner summary.

Task 6: Document Environment Variables and Configuration

Under-documented .env files cause endless onboarding pain. Claude can generate a .env.example with full explanations from your existing code.

Prompt:

Search this codebase for all environment variable references (process.env.*, import.meta.env.*).

[paste relevant files or a list of env vars]

Generate:
1. A .env.example file with placeholder values and comments explaining each variable
2. A "Configuration" section for the README that groups variables by category (database, auth, external APIs, feature flags) and marks which ones are required vs optional

Sample output:

bash# ─────────────────────────────────────────────
# DATABASE
# ─────────────────────────────────────────────

# Neon PostgreSQL connection string (required)
# Format: postgresql://user:password@host/database?sslmode=require
DATABASE_URL=

# Connection pool size per serverless instance (optional, default: 5)
DATABASE_POOL_SIZE=5

# ─────────────────────────────────────────────
# AUTHENTICATION
# ─────────────────────────────────────────────

# NextAuth.js secret — generate with: openssl rand -base64 32 (required)
NEXTAUTH_SECRET=

# OAuth callback URL — must match provider settings exactly (required)
NEXTAUTH_URL=http://localhost:3000


Task 7: Generate Architecture Documentation (ADRs)

Architecture Decision Records (ADRs) capture why a technical decision was made, not just what was decided. Teams that skip them spend hours in meetings relitigating solved problems.

Prompt:

I made the following architectural decision: [describe the decision, e.g., "switched from REST to tRPC for our internal API layer"].

Write an Architecture Decision Record (ADR) in the Nygard format:
- Title
- Status (Accepted)
- Context — what problem we were solving and constraints
- Decision — what we chose and why
- Consequences — what becomes easier, what becomes harder, what we're accepting as a trade-off

Here is additional context about why we made this choice:
[explain your reasoning]

ADRs stored alongside code (e.g., docs/decisions/) become searchable institutional memory. When a new developer asks "why is this a monorepo?", the ADR has the answer.


Setting Up a Documentation Workflow With Claude Code

If you use Claude Code, you can automate documentation tasks as part of your development workflow using hooks.

Add this to your CLAUDE.md:

markdown## Documentation Rules
- After writing any new exported function, generate JSDoc annotations
- After merging a feature branch, generate a CHANGELOG entry
- If a new environment variable is added, update .env.example immediately

With this in place, Claude Code will follow these rules mid-session without being prompted. Documentation stops being an afterthought and becomes part of the build.


Prompt Templates Quick Reference

TaskKey Instruction
README"The audience is [X]. Follow this structure: [sections]"
Inline comments"Do NOT comment self-evident code"
JSDoc"Include @throws and @example for every function"
OpenAPI spec"Include 400, 401, 404, 500 response schemas"
CHANGELOG"Follow Keep a Changelog format, flag breaking changes"
.env docs"Group by category, mark required vs optional"
ADR"Use Nygard format, explain the trade-offs honestly"

Key Takeaways

  • Claude maintains your documentation conventions within a session — define them once, apply everywhere
  • The highest-leverage use is legacy code: inline comments and JSDoc for code that was never documented
  • OpenAPI spec generation from route handlers can replace 3-4 hours of manual work before each API review
  • Combine with Claude Code hooks to make documentation automatic, not optional


Next Steps

Ready to go deeper on Claude for development?

If you're serious about building with Claude, the Claude Certified Architect (CCA-F) certification validates your ability to design and ship production-grade AI systems — not just use the chat interface. Our practice test bank covers architecture patterns, prompt design, and agentic workflows.

Ready to Start Practicing?

300+ scenario-based practice questions covering all 5 CCA domains. Detailed explanations for every answer.

Free CCA Study Kit

Get domain cheat sheets, anti-pattern flashcards, and weekly exam tips. No spam, unsubscribe anytime.