Good API documentation is the difference between developers adopting your API in an afternoon and abandoning it after thirty frustrated minutes. But writing docs is tedious, and most teams either skip it or produce minimal reference pages that answer "what" without explaining "how" or "why."
AI can generate solid API documentation — but only if you give it enough technical context. "Write docs for my API" produces vague boilerplate. The patterns below produce documentation that developers actually want to read.
These five patterns cover the core API documentation tasks: endpoint reference pages, integration quickstart guides, error handling documentation, SDK code examples, and migration guides.
Pattern 1: The Endpoint Reference Page
Every API endpoint needs a clear, consistent reference page. This pattern generates one that follows documentation best practices.
The Template
You are a technical writer creating API reference documentation.
Write documentation for the following API endpoint:
Endpoint details:
- Method and path: [e.g., POST /api/v2/users]
- Purpose: [what this endpoint does in one sentence]
- Authentication: [how the endpoint is authenticated — API key, Bearer token, OAuth, none]
- Request parameters:
[list each parameter with: name, type, required/optional, description]
- Request body (if applicable):
[provide the JSON schema or an example request body]
- Response:
[provide an example success response with status code]
- Error responses:
[list common error codes and when they occur]
Documentation structure:
1. Endpoint title and one-line description
2. HTTP method, URL, and authentication requirements
3. Parameters table (name, type, required, description)
4. Example request (with curl and one programming language — [specify: Python/JavaScript/Go/etc.])
5. Example success response with field descriptions
6. Error responses table with status code, error message, and common cause
7. Notes: any rate limits, pagination details, or important caveats
Constraints:
- Use consistent formatting that could be pasted into a docs site
- Example requests should use realistic but obviously fake data (e.g., "user@example.com", not real emails)
- Include the full curl command with all required headers
- If I have not provided enough information about error cases, flag it rather than inventing error responses
- Tone: clear, precise, no unnecessary words
Why It Works
The dual code example requirement (curl plus one language) ensures the documentation is useful for both quick testing and actual implementation. Flagging missing error cases rather than inventing them prevents documentation from making promises the API does not keep — a common and dangerous problem.
Example Output
For a user creation endpoint:
## Create User
Creates a new user account and returns the user object.
>
POST /api/v2/users
>
Authentication: Bearer token required
>
### Parameters
>
| Name | Type | Required | Description |
|------|------|----------|-------------|
| email | string | Yes | User's email address. Must be unique. |
| name | string | Yes | Display name. 1-100 characters. |
| role | string | No | User role. One of:admin,member,viewer. Defaults tomember. |
>
### Example Request
>
curl:
bash> curl -X POST https://api.example.com/api/v2/users \ > -H "Authorization: Bearer your_api_key_here" \ > -H "Content-Type: application/json" \ > -d '{ > "email": "jane@example.com", > "name": "Jane Smith", > "role": "member" > }' >
>
Python:
python> import requests > > response = requests.post( > "https://api.example.com/api/v2/users", > headers={"Authorization": "Bearer your_api_key_here"}, > json={ > "email": "jane@example.com", > "name": "Jane Smith", > "role": "member" > } > ) > print(response.json()) >
>
### Success Response
>
Status: 201 Created
json> { > "id": "usr_abc123", > "email": "jane@example.com", > "name": "Jane Smith", > "role": "member", > "created_at": "2026-04-13T10:30:00Z" > } >
>
### Error Responses
>
| Status | Error | Cause |
|--------|-------|-------|
| 400 | invalid_email | Email format is invalid |
| 409 | email_exists | A user with this email already exists |
| 401 | unauthorized | Missing or invalid Bearer token |
| 422 | invalid_role | Role value is not one of the accepted options |
>
### Notes
- Rate limit: 100 requests per minute per API key
- Email addresses are case-insensitive and stored lowercase
Pattern 2: The Integration Quickstart Guide
Developers want to go from "I have an API key" to "I made my first successful call" in under five minutes. This pattern creates that quickstart experience.
The Template
You are a developer advocate writing a quickstart guide for a new API user.
Create an integration quickstart for [API name/service].
API context:
- What the API does: [one-sentence description]
- Authentication method: [API key, OAuth, etc.]
- Base URL: [the API base URL]
- Most common first action: [what new users typically want to do first]
- Language/framework: [write the guide for this language — Python, JavaScript, etc.]
Quickstart structure:
1. Prerequisites: What the developer needs before starting (3-5 bullet points max)
2. Step 1 — Get credentials: Where to find or generate the API key/token
3. Step 2 — Install dependencies: The specific package or library to install (with exact command)
4. Step 3 — Make your first call: A complete, runnable code example for the most common action
5. Step 4 — Handle the response: How to parse the response and what each field means
6. Step 5 — Common next steps: 2-3 links or descriptions of what to do after the first call works
Constraints:
- The code must be complete and runnable — a developer should be able to copy-paste it and have it work (assuming valid credentials)
- Include error handling in the code example — show what to do when the call fails
- No boilerplate or filler text — every sentence should move the developer forward
- Use realistic example data that is obviously fake
- Total length: under 400 words of prose (code blocks do not count toward the limit)
- Tone: direct and helpful — like a senior developer walking a teammate through setup
Why It Works
The "complete and runnable" constraint is essential. Most quickstart guides include code snippets that require modifications or additional context to actually work. This template produces code a developer can copy directly. Including error handling in the first example establishes good practices from the start.
Example Output
For a weather data API, Python quickstart:
## Quickstart: Get Weather Data in 5 Minutes
>
### Prerequisites
- Python 3.8 or later
- An API key (sign up at dashboard.example.com/api-keys)
- pip package manager
>
### Step 1: Get your API key
After signing up, go to Dashboard > API Keys > Create Key. Copy the key — you will not be able to see it again.
>
### Step 2: Install the SDK
bash> pip install weather-sdk >
>
### Step 3: Get current weather for a location
python> from weather_sdk import WeatherClient > from weather_sdk.exceptions import APIError, AuthenticationError > > client = WeatherClient(api_key="your_api_key_here") > > try: > weather = client.get_current(city="San Francisco", units="imperial") > print(f"Temperature: {weather.temperature}°F") > print(f"Conditions: {weather.description}") > print(f"Humidity: {weather.humidity}%") > except AuthenticationError: > print("Invalid API key. Check your credentials.") > except APIError as e: > print(f"API error: {e.status_code} — {e.message}") >
>
### Step 4: Understanding the response
The weather object contains:
- temperature — Current temperature in your specified units
- description — Human-readable conditions (e.g., "Partly Cloudy")
- humidity — Relative humidity percentage
- wind_speed — Wind speed in your specified units
- timestamp — UTC timestamp of the observation
>
### Step 5: Next steps
- Forecasts: Use client.get_forecast(city, days=7) for multi-day predictions
- Bulk locations: Pass a list of cities to client.get_bulk() for a single batched request
- Webhooks: Set up weather alerts at dashboard.example.com/webhooks
Pattern 3: The Error Handling Reference
Good error documentation saves developers more time than any other part of the docs. This pattern creates a comprehensive error reference that helps developers debug problems quickly.
The Template
You are a technical writer creating an error handling guide for an API.
API context:
- API name: [name]
- Common error scenarios: [list the types of errors developers encounter]
- Error response format:
[provide the standard error response JSON structure]
Create an error handling reference with:
1. Error response format: Explain the standard structure of all error responses
2. Error code reference: For each error code/type, provide:
- HTTP status code
- Error code string
- What it means (one sentence)
- Common cause (what the developer probably did wrong)
- How to fix it (specific action to take)
- Example error response (JSON)
3. Debugging checklist: A step-by-step troubleshooting flow for when a developer gets an unexpected error
4. Code example: Show how to implement proper error handling in [language] — catching errors, logging useful context, and retrying when appropriate
Constraints:
- Organize errors by HTTP status code category (4xx client errors, 5xx server errors)
- "How to fix it" must be actionable — "check your request" is not helpful, "verify the email field is a valid email format with an @ symbol and domain" is helpful
- Include at least one error that is commonly confusing or misleading, and explain the actual cause
- Do not invent error codes that my API does not use — flag any gaps
- Tone: empathetic — developers reading error docs are already frustrated
Why It Works
The "how to fix it must be actionable" constraint transforms error docs from a status code glossary into a debugging guide. Including commonly misleading errors addresses the cases where developers waste the most time. The debugging checklist provides a systematic approach instead of random trial and error.
Example Output
For a payment processing API:
## Error Response Format
>
All errors return a JSON object with this structure:
json> { > "error": { > "code": "invalid_card", > "message": "The card number is not valid.", > "param": "card_number", > "request_id": "req_abc123" > } > } >
>
Always include the request_id when contacting support — it links directly to the server-side logs for your request.
>
## Client Errors (4xx)
>
### 400 — invalid_card
Means: The card number failed validation.
Common cause: Typo in the card number, or passing a test card number in production mode.
Fix: Verify the card number is correct and that you are using the right mode (test vs. production). Test card numbers only work with test API keys.
>
### 400 — insufficient_funds
Means: The card does not have enough funds for the transaction.
Common cause: This is a legitimate decline from the card issuer, not a bug in your integration.
Fix: Prompt the user to try a different payment method. Do not retry the same card — repeated attempts can trigger fraud alerts.
>
### 401 — authentication_failed
Means: The API key is missing, malformed, or revoked.
Common cause: Using a test key in production, or the key was rotated and your application still uses the old one.
Fix: Check that yourAuthorizationheader isBearer sk_live_...(production) orBearer sk_test_...(test). Verify the key has not been revoked in your dashboard.
>
### 402 — card_declined
Note — this is commonly confused withinsufficient_funds. Acard_declinedresponse means the issuing bank rejected the transaction, but the reason is not disclosed. It could be fraud protection, spending limits, or account restrictions. Unlikeinsufficient_funds, you get no additional detail.
Fix: Ask the user to contact their bank or try a different card. Do not display the raw error code to the user — show a friendly message like "Your card was declined. Please try another payment method."
>
## Debugging Checklist
>
When you get an unexpected error:
1. Check the error.code against this reference
2. Verify you are using the correct API key for your environment (test vs. production)
3. Log the full error response including request_id
4. Check the request body matches the expected format (missing fields often cause unhelpful 400 errors)
5. If the error is intermittent, check the API status page before investigating your code
Pattern 4: The SDK Code Example Generator
Developers learn by example. This pattern generates complete, well-commented code examples for common API workflows.
The Template
You are a developer writing code examples for API documentation.
Create a complete code example for the following workflow:
Workflow: [describe the multi-step task — e.g., "create a customer, add a payment method, and process a charge"]
Language: [programming language]
API details:
- Base URL: [URL]
- Authentication: [method]
- Endpoints involved: [list the endpoints this workflow uses]
- Required data: [what information is needed to complete the workflow]
Code requirements:
1. Complete and runnable — include imports, configuration, and a main function or script entry point
2. Show each API call with proper error handling
3. Include comments explaining why each step is necessary, not just what it does
4. Handle common failure points (authentication errors, validation errors, network timeouts)
5. Use environment variables for sensitive values (API keys, secrets)
6. Follow the language's idioms and conventions (e.g., async/await in JavaScript, context managers in Python)
Output format:
- Full code example
- Below the code: a numbered walkthrough explaining each section (3-5 sentences per section)
- A "Common modifications" section listing 2-3 ways developers might customize this example
Constraints:
- Do not use deprecated methods or outdated syntax
- Use the language's standard HTTP library or the official SDK — not third-party wrappers
- Fake data should be obviously fake (use example.com domains, placeholder names)
- Code should handle both success and failure paths
- Tone: clear, precise comments — no joke comments or unnecessary verbosity
Why It Works
The "why, not what" comment requirement elevates the code from a copy-paste snippet to a learning tool. Developers can read the comments, understand the reasoning, and adapt the code to their needs. The walkthrough and common modifications sections anticipate follow-up questions.
Example Output
For a JavaScript workflow: create a customer and process a payment:
javascript> import { PaymentClient } from 'payment-sdk'; > > // Load API key from environment — never hardcode credentials > const client = new PaymentClient({ > apiKey: process.env.PAYMENT_API_KEY, > environment: process.env.NODE_ENV === 'production' ? 'live' : 'sandbox' > }); > > async function processFirstPayment(customerEmail, cardToken, amountCents) { > try { > // Step 1: Create the customer record first — this gives us a > // stable ID to associate payments with, even if the card changes later > const customer = await client.customers.create({ > email: customerEmail, > metadata: { source: 'checkout_page' } > }); > console.log(`Customer created: ${customer.id}`); > > // Step 2: Attach the payment method to the customer > // The cardToken comes from your frontend — it's a one-time-use > // token that represents the card without exposing the card number > const paymentMethod = await client.paymentMethods.attach({ > customerId: customer.id, > token: cardToken > }); > > // Step 3: Process the charge > // Amount is in cents to avoid floating-point rounding issues > const charge = await client.charges.create({ > customerId: customer.id, > paymentMethodId: paymentMethod.id, > amount: amountCents, > currency: 'usd', > description: 'First purchase' > }); > > if (charge.status === 'succeeded') { > console.log(`Payment successful: ${charge.id}`); > return { success: true, chargeId: charge.id }; > } else { > // Some charges require additional authentication (3D Secure) > console.log(`Payment requires action: ${charge.status}`); > return { success: false, status: charge.status, nextAction: charge.next_action }; > } > > } catch (error) { > if (error.code === 'card_declined') { > return { success: false, error: 'Card was declined. Try another payment method.' }; > } > if (error.code === 'authentication_failed') { > throw new Error('API key is invalid. Check PAYMENT_API_KEY environment variable.'); > } > // Unexpected errors — log the full error for debugging > console.error('Unexpected payment error:', error); > throw error; > } > } > > // Usage > processFirstPayment('jane@example.com', 'tok_test_visa', 2999) > .then(result => console.log(result)) > .catch(err => console.error(err)); >
>
Walkthrough:
>
1. Configuration (lines 1-5): The client is initialized with an API key from the environment and auto-selects sandbox or live mode based on NODE_ENV. This prevents accidentally processing real charges during development.
>
2. Customer creation (lines 9-13): Creating the customer first establishes a record that persists across sessions. If the charge fails, you still have the customer on file for retry without re-collecting their information.
>
3. Payment method attachment (lines 17-20): The card token is a secure, single-use reference generated by the frontend SDK. Attaching it to the customer converts it to a reusable payment method.
>
4. Charge processing (lines 24-36): The charge checks for both success and pending states. Some banks require 3D Secure verification, which returns a requires_action status with a URL to redirect the user.
>
5. Error handling (lines 38-48): Card declines are handled as a user-facing message, authentication errors surface a developer-facing message, and unexpected errors are logged with full context.
>
Common modifications:
- Subscription billing: Replacecharges.create()withsubscriptions.create()and pass apriceIdinstead of an amount
- Idempotency: Add an idempotencyKey to the charge to prevent duplicate charges on network retries
- Metadata: Add custom key-value pairs to the charge's metadata field for reconciliation with your internal systems
Pattern 5: The Migration Guide
When your API has a new version, developers need a clear path from the old one to the new one. This pattern generates a migration guide that minimizes confusion and missed steps.
The Template
You are a technical writer creating a migration guide for API version changes.
Migration context:
- Current version: [e.g., v1]
- New version: [e.g., v2]
- Deprecation timeline: [when the old version stops working]
- Breaking changes:
[list each breaking change — renamed fields, removed endpoints, changed behavior, new required parameters]
- New features in the new version:
[list features that are new, not just changed]
Create a migration guide with:
1. Overview: What is changing and why (2-3 sentences — not a sales pitch for v2, just the facts)
2. Timeline: Key dates — when v2 is available, when v1 is deprecated, when v1 is shut down
3. Breaking changes: For each change, provide:
- What changed (old vs. new, side by side)
- Why it changed (one sentence of context)
- How to update your code (before/after code example)
- Gotchas or edge cases to watch for
4. Non-breaking changes: Things that are new or different but do not require code changes
5. Migration checklist: A step-by-step list developers can follow to migrate
6. Testing recommendations: How to verify the migration works before switching over
Constraints:
- Order breaking changes from highest impact to lowest
- Show before/after code for every breaking change — no "update your code to use the new field name" without showing the actual code
- Be explicit about which changes require immediate action vs. which can be done gradually
- If there is a way to support both versions during transition, explain how
- Tone: empathetic and precise — developers dread migration guides, so make this one painless
Why It Works
The before/after code requirement eliminates the most common complaint about migration guides: "it tells me something changed but not exactly what to do about it." Ordering by impact helps developers prioritize. The gotchas section catches the edge cases that cause unexpected failures after migration.
Example Output
For an API migrating from v1 to v2 with renamed fields and a new required parameter:
## Migration Guide: v1 to v2
>
### Overview
Version 2 standardizes field naming to camelCase, adds required pagination parameters to list endpoints, and introduces webhook signature verification. The v1 API will continue to function until December 31, 2026.
>
### Timeline
- Now: v2 is available at api.example.com/v2/
- September 1, 2026: v1 endpoints begin returning deprecation warnings in response headers
- December 31, 2026: v1 is shut down and all requests return 410 Gone
>
### Breaking Change 1: Field naming (snake_case to camelCase)
>
All response fields have been renamed from snake_case to camelCase.
>
Impact: High — affects every endpoint.
>
Before (v1):
json> { "user_id": "usr_123", "created_at": "2026-01-01T00:00:00Z" } >
>
After (v2):
json> { "userId": "usr_123", "createdAt": "2026-01-01T00:00:00Z" } >
>
How to update: Search your codebase for all v1 field names and update them. If you use a typed language, update your type definitions first — the compiler will surface every location that needs updating.
>
Gotcha: If you store raw API responses in a database, you will need to either migrate the stored data or add a translation layer when reading old records.
>
### Migration Checklist
- [ ] Update base URL from/v1/to/v2/
- [ ] Rename all response field references from snake_case to camelCase
- [ ] Addlimitandoffsetparameters to all list endpoint calls
- [ ] Implement webhook signature verification
- [ ] Run your test suite against the v2 sandbox
- [ ] Monitor error rates for 48 hours after switching production traffic
Quick Tips for API Documentation Prompts
- Paste your actual API schema. If you have an OpenAPI spec, Swagger definition, or even route definitions from your codebase, paste them directly. The more real data the AI has, the less it invents.
- Specify the audience's skill level. Documentation for junior developers who are new to APIs reads very differently from docs for senior engineers who just need the reference.
- Include your error response format. The AI cannot generate accurate error documentation without knowing your actual error structure.
- Ask for multiple languages. If your users work in different languages, generate examples in Python, JavaScript, and curl in a single prompt.
- Review the generated code. AI-generated code examples should always be tested before publishing. Treat the output as a draft, not a final version.
When to Use Templates vs. Freeform Prompts
Use these templates for systematic documentation work — launching a new API, documenting all endpoints, or creating a migration guide for a version bump. The structure ensures completeness and consistency across all your docs.
Go freeform when answering a specific developer question, explaining a nuanced behavior, or writing a one-off tutorial for a unique integration scenario. For those, use the CRAFT framework from our prompt writing guide to provide enough context for a good response.
For instant prompt generation without building templates manually, SurePrompts' AI Prompt Generator can structure your technical writing requests automatically.