Code Documentation Prompt Templates
AI prompt templates for writing code documentation. Create clear comments, READMEs, and API docs.
Overview
Good documentation is the difference between code that can be maintained and code that becomes technical debt. These prompts help you write documentation that developers actually read, READMEs that answer real questions, API docs that reduce support requests, and code comments that explain the 'why' not the 'what'. The trick is generating docs that stay useful as code evolves.
Best Practices
Specify your audience, documentation for API consumers differs vastly from internal team docs
Include the current state of documentation so the AI can maintain consistency in style and format
Provide examples of good documentation from your project to match tone and depth
Focus on the 'why' for inline comments, the code shows 'what', comments should explain reasoning
Request documentation that's easy to maintain, avoid hardcoding values that will change
Prompt Templates
1. README Generator
Generate a README.md for this project: **Project name:** [NAME] **What it does:** [ONE-SENTENCE DESCRIPTION] **Tech stack:** [LANGUAGES, FRAMEWORKS, KEY DEPENDENCIES] **Target users:** [WHO WILL USE THIS] **Key features:** - [FEATURE 1] - [FEATURE 2] - [FEATURE 3] **Installation requires:** [PREREQUISITES - e.g. Node 18+, Docker, API keys] **Include sections for:** - Quick start (get running in under 5 minutes) - Installation - Configuration/environment variables - Basic usage examples - Contributing guidelines - License Tone: [PROFESSIONAL / CASUAL / TECHNICAL]
Project: FastCache What it does: In-memory caching library with automatic expiration Tech stack: TypeScript, Node.js Target users: Backend developers Features: TTL support, LRU eviction, clustering Prerequisites: Node 16+
# FastCache
A lightweight, high-performance in-memory caching library for Node.js with automatic expiration and LRU eviction.
## Quick Start
```bash
npm install fastcache
```
```typescript
import { Cache } from 'fastcache';
const cache = new Cache({ maxSize: 1000, ttl: 60000 });
cache.set('user:123', userData);
const user = cache.get('user:123');
```
## Features
- **TTL Support** - Automatic expiration with per-key TTL
- **LRU Eviction** - Memory-efficient with least-recently-used eviction
- **Clustering** - Distributed cache across Node.js cluster workers
[Continues with full sections...]Starting new projects, open-sourcing internal tools, or improving project discoverability
- •The Quick Start section is the most read, make it actually quick (5 minutes or less)
- •Include copy-pasteable code examples that work out of the box
2. API Documentation Generator
Generate API documentation for this endpoint: **Endpoint:** [METHOD] [PATH] **Purpose:** [WHAT IT DOES] **Authentication:** [REQUIRED AUTH METHOD] **Request details:** ```[LANGUAGE] [REQUEST BODY SCHEMA OR EXAMPLE] ``` **Response details:** ```[LANGUAGE] [RESPONSE BODY SCHEMA OR EXAMPLE] ``` **Error cases:** - [ERROR SCENARIO 1] - [ERROR SCENARIO 2] **Document in format:** [OPENAPI / MARKDOWN / CUSTOM] Include: description, parameters, request/response examples, error responses, and rate limits if applicable.
Endpoint: POST /api/v1/users
Purpose: Create a new user account
Auth: API key in header
Request: { email, password, name }
Response: { id, email, name, created_at }
Errors: Email already exists, invalid email format, weak password## Create User
Creates a new user account and returns the user object.
### Request
`POST /api/v1/users`
**Headers:**
| Header | Required | Description |
|--------|----------|-------------|
| X-API-Key | Yes | Your API key |
| Content-Type | Yes | application/json |
**Body:**
```json
{
"email": "user@example.com",
"password": "securePassword123!",
"name": "Jane Doe"
}
```
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| email | string | Yes | Valid email address |
| password | string | Yes | Min 8 chars, 1 uppercase, 1 number |
| name | string | Yes | User's display name |
### Response
**Success (201 Created):**
```json
{
"id": "usr_abc123",
"email": "user@example.com",
"name": "Jane Doe",
"created_at": "2024-01-15T10:30:00Z"
}
```
### Errors
| Status | Code | Description |
|--------|------|-------------|
| 400 | INVALID_EMAIL | Email format is invalid |
| 400 | WEAK_PASSWORD | Password doesn't meet requirements |
| 409 | EMAIL_EXISTS | Email already registered |Documenting REST APIs, creating API references, or generating OpenAPI specs
- •Include realistic example values, not 'string' or 'example', developers copy-paste these
- •Document error responses as thoroughly as success responses
3. Function Documentation Generator
Generate documentation for this function/method: ```[LANGUAGE] [PASTE FUNCTION CODE] ``` **Context:** - Part of: [MODULE/CLASS NAME] - Used by: [WHO CALLS THIS] - Side effects: [ANY SIDE EFFECTS - database writes, API calls, etc.] **Documentation format:** [JSDOC / DOCSTRING / JAVADOC / XMLDOC] Include: - Clear description of purpose - Parameter descriptions with types and constraints - Return value description - Exceptions/errors that can be thrown - Usage example - Any important notes or warnings
Language: Python Function: process_payment() that handles Stripe charges Context: Part of PaymentService class, called by checkout endpoint Side effects: Creates Stripe charge, updates database order status Format: Python docstring
```python def process_payment( order_id: str, payment_method_id: str, amount_cents: int, idempotency_key: str | None = None ) -> PaymentResult: """ Process a payment through Stripe and update order status. Charges the customer's payment method and marks the order as paid if successful. Uses idempotency keys to prevent duplicate charges. Args: order_id: The order to process payment for. Must exist in database. payment_method_id: Stripe payment method ID (pm_xxx). amount_cents: Amount to charge in cents. Must be positive. idempotency_key: Optional key for idempotent requests. If not provided, generates one from order_id. Returns: PaymentResult with status, charge_id, and any error details. Raises: OrderNotFoundError: If order_id doesn't exist. PaymentDeclinedError: If card is declined or invalid. StripeConnectionError: If Stripe API is unreachable. Example: >>> result = payment_service.process_payment( ... order_id="ord_123"... payment_method_id="pm_card_visa"... amount_cents=2999 ... ) >>> result.status 'succeeded' Note: This method is NOT idempotent without an idempotency_key. Always provide one for retry logic. """ ```
Documenting complex functions, public APIs, or functions with important side effects
- •The 'Note' or 'Warning' section is important for gotchas, document anything surprising
- •Include a runnable example, not just a description
4. Code Comment Enhancer
Add meaningful comments to this code: ```[LANGUAGE] [PASTE CODE WITHOUT COMMENTS] ``` **Guidelines:** - Don't comment obvious things (// increment i) - DO explain: business logic, workarounds, non-obvious algorithms, why not just what - Highlight any: gotchas, assumptions, TODOs, or temporary code **Comment style:** [BRIEF / DETAILED / ONLY COMPLEX PARTS] Return the code with appropriate comments added.
Language: JavaScript Code: Function that calculates shipping cost with various rules Style: Only complex parts
```javascript
function calculateShipping(cart, destination) {
const baseRate = 5.99;
let total = 0;
// Free shipping threshold varies by membership tier
// Premium: $35, Standard: $50, Guest: $75
const freeShippingThreshold = getFreeThreshold(cart.membershipTier);
if (cart.subtotal >= freeShippingThreshold) {
return 0;
}
// Weight-based calculation for items over 5lbs
// Using dimensional weight if greater than actual weight
// (carrier billing policy as of 2024)
for (const item of cart.items) {
const dimWeight = (item.length * item.width * item.height) / 139;
const billedWeight = Math.max(item.weight, dimWeight);
if (billedWeight > 5) {
// Rate increases $2 per lb over 5lbs, capped at $25 surcharge
total += Math.min((billedWeight - 5) * 2, 25);
}
}
// Hawaii/Alaska surcharge (USPS Zone 8 rates)
// TODO: Refactor when we add international shipping
if (['HI', 'AK'].includes(destination.state)) {
total += 12.99;
}
return baseRate + total;
}
```Improving readability of complex code, preparing code for handoff, or documenting business rules
- •Comments explaining 'why' age better than comments explaining 'what'
- •Add TODOs for known technical debt so it's not forgotten
Common Mistakes to Avoid
Generating generic documentation that doesn't reflect the specific codebase or domain terminology
Over-documenting obvious code while leaving complex business logic unexplained
Creating documentation that's immediately outdated because it hardcodes values that change
Frequently Asked Questions
Good documentation is the difference between code that can be maintained and code that becomes technical debt. These prompts help you write documentation that developers actually read, READMEs that answer real questions, API docs that reduce support requests, and code comments that explain the 'why' not the 'what'. The trick is generating docs that stay useful as code evolves.
Related Templates
Code Review Prompt Templates
AI prompt templates for thorough code reviews. Get comprehensive feedback on code quality, security, and best practices.
Debugging Prompt Templates
AI prompt templates for debugging code. Identify issues, understand errors, and find solutions faster.
API Design Prompt Templates
AI prompt templates for designing APIs. Create well-structured, intuitive API endpoints and documentation.
Have your own prompt to optimize?