Intermediate

AI Prompts for API Documentation

Great API documentation is the single biggest factor in developer adoption. Stripe, Twilio, and SendGrid built billion-dollar businesses partly on the strength of their developer experience — and documentation sits at the center of that experience.

Yet writing documentation is almost universally disliked by engineering teams. It is repetitive, detail-oriented work that pulls developers away from building features. The result is documentation that is outdated, incomplete, or simply never written.

AI changes this equation. With the right prompts, you can generate first-pass documentation from code, maintain consistency across hundreds of endpoints, and produce multi-language SDK examples in minutes rather than hours. This guide covers the full documentation lifecycle with production-tested prompts.

Why Most API Documentation Fails

Before diving into prompts, it is worth understanding the common failure modes of API documentation:

  • Incomplete reference: Missing request/response schemas, undocumented error codes, or vague parameter descriptions.
  • No getting started guide: Developers land on a reference page with no path to their first successful API call.
  • Stale examples: Code examples use deprecated syntax or refer to old versions.
  • Poor error guidance: Error codes without explanation of how to fix the underlying problem.
  • Inconsistent style: One endpoint uses "user_id", another uses "userId", and a third uses "id".

AI is particularly effective at addressing the first four problems. Consistency enforcement (the fifth) works best when combined with a style guide that the AI can reference.

From Code to OpenAPI 3.0 Spec

If you have a working API but no formal specification, generating an OpenAPI document is the highest-leverage first step. The spec becomes the foundation for documentation, SDK generation, and API testing.

Generate an OpenAPI 3.0 specification for this REST API.

BASE URL: https://api.example.com/v1

ENDPOINTS (paste relevant code or list them):
- GET /users
- GET /users/{id}
- POST /users
- PUT /users/{id}
- DELETE /users/{id}
- GET /orders?user_id={id}
- POST /orders

AUTHENTICATION: Bearer token with JWT

Please include:
1. All paths with correct HTTP methods and summary sentences
2. Request parameters (path, query, header, cookie) with types and descriptions
3. Request bodies with JSON schema definitions
4. Response schemas for 200, 400, 401, 404, 422, 429, and 500
5. Example request and response payloads for each endpoint
6. Any enum values with descriptions
7. Tags grouping related endpoints

Output as a valid YAML OpenAPI spec.

Tips for Better OpenAPI Generation

The quality of the generated spec depends heavily on what you feed into the prompt:

  • Include type annotations: If you are pasting code from a typed language (TypeScript, Python with type hints, Go), the AI will infer correct schema types. Untyped code leads to generic "string" types.
  • Provide one complete example: If your API follows a pattern (e.g., standard CRUD for multiple resources), show one resource fully implemented and ask the AI to generate the others following the same pattern.
  • Validate the output: Paste the generated YAML into an OpenAPI validator (Swagger Editor) before committing it.

Writing Individual Endpoint Documentation

Once you have a spec, you need prose documentation that explains each endpoint in developer-friendly language. Here is a prompt that produces a complete documentation page for a single endpoint:

Write developer-facing documentation for this API endpoint.

ENDPOINT: POST /api/v1/orders

PURPOSE: Create a new order in the system

REQUEST BODY (JSON):
{
  "user_id": "string (required) - The customer placing the order",
  "items": [
    {
      "product_id": "string (required)",
      "quantity": "integer (required, min: 1)",
      "variant_id": "string (optional) - For size/color options"
    }
  ],
  "shipping_address": {
    "street": "string (required)",
    "city": "string (required)",
    "country": "string (required, ISO 3166-1 alpha-2)"
  },
  "promo_code": "string (optional)"
}

RESPONSES:
- 201 Created: Order successfully created. Returns order object with ID.
- 400 Bad Request: Invalid JSON or missing required fields.
- 401 Unauthorized: Missing or invalid Bearer token.
- 409 Conflict: Product out of stock for requested quantity.
- 422 Unprocessable Entity: Shipping address validation failed.

AUTHENTICATION: Bearer token required. Scope: orders:write

Please produce documentation with:
1. A one-line summary of what this endpoint does
2. A paragraph explaining when to use it and behavior details
3. A complete request example in cURL
4. A complete request example in Python (requests library)
5. A complete request example in JavaScript (fetch API)
6. A 201 success response body example
7. Error response examples for 400, 401, and 422
8. Rate limit information
9. A note about idempotency (is calling twice safe?)

Multi-Language SDK Examples

Developer surveys consistently show that SDK examples in a developer's preferred language are the most valued part of API documentation. Generating these by hand is tedious; generating them with AI is fast.

For this API endpoint, generate complete, runnable examples:

ENDPOINT: GET /api/v1/users/{id}
AUTHENTICATION: Bearer token via Authorization header
RESPONSE: User object with id, email, name, created_at, role

Generate examples in these languages:
1. Python (using requests)
2. JavaScript/Node.js (using fetch)
3. Go (using net/http and encoding/json)
4. Ruby (using net/http)
5. PHP (using curl)

Each example must:
- Be complete enough to copy, paste, and run with minimal changes
- Include proper error handling (non-2xx status codes)
- Include a comment indicating where to insert the API key
- Use standard library or the most common HTTP package for the language
- Follow each language's idioms (not a direct translation from Python)
- Be concise but not cryptic

Why Multi-Language Examples Matter

A 2023 Postman developer survey found that 58% of developers abandon an API if documentation lacks examples in their preferred language. The most requested languages are Python, JavaScript, Java, C#, and Go. We recommend covering at least your top three user languages rather than all of them superficially.

Generating FAQ and Troubleshooting Sections

Reference documentation answers "how." FAQ answers "why" and troubleshooting answers "what went wrong." Both reduce support burden significantly.

My API has these endpoints:
[LIST ENDPOINTS AND COMMON ERRORS]

Based on our support ticket data, these are the top 10 questions developers ask:
1. "Why am I getting 401 even though my token looks correct?"
2. "How do I paginate through large result sets?"
3. "What is the rate limit and how do I handle 429?"
4. "Can I filter results by multiple fields at once?"
5. "Why is my webhook not receiving events?"
6. "How do I handle retries for failed requests?"
7. "What timezone are dates returned in?"
8. "Can I batch multiple operations in one request?"
9. "How do I know when a resource has been updated?"
10. "What happens to my data if I cancel my subscription?"

Please generate:
1. Each question as a FAQ item with a clear answer (100-150 words each)
2. A troubleshooting flowchart in text form for the 401 error
3. A "Common Errors" table with columns: Error Code, When It Happens, How to Fix It
4. One "Pro Tip" per section that goes beyond the obvious answer

Enforcing Documentation Style Guides

As documentation grows, maintaining consistent voice, formatting, and terminology becomes difficult. AI can audit existing docs against your style guide.

Review this API documentation against our style guide:

STYLE RULES:
- Headings use sentence case ("Create an order" not "Create An Order")
- Address the reader as "you"
- Include a code example for every endpoint
- Error responses must include a "how to fix" note
- Parameter tables include Type, Required, Description, and Example columns
- Use "Deprecated" badges on endpoints scheduled for removal
- All dates use ISO 8601 format in examples

DOCUMENTATION TO REVIEW:
[PASTE DOCUMENTATION TEXT]

Please provide:
1. A list of style violations with line references
2. Corrected text for each violation
3. A list of missing information (examples, error handling, etc.)
4. An overall quality score from 1-10 with reasoning

Developer Onboarding Guides

Getting started docs are the most critical but most neglected part of API documentation. A developer should go from zero to a successful API call in under 10 minutes.

Write a "Getting Started" guide for developers using our API.

API OVERVIEW:
- Base URL: https://api.example.com/v1
- Authentication: Bearer token (obtained from /auth/token)
- Primary resources: Users, Orders, Products
- Rate limit: 100 requests/minute
- Data format: JSON

GUIDE REQUIREMENTS:
1. Prerequisites (what the developer needs before starting)
2. Step 1: Obtaining an API key (include a real cURL example)
3. Step 2: Making the first request (a simple GET that should work)
4. Step 3: A slightly more complex request (POST with a body)
5. What the success response looks like (with actual JSON)
6. What a common error looks like and how to fix it
7. Where to go next (link to reference docs and SDKs)

Tone: Encouraging but not condescending. Assume the reader is a competent developer who is new to this API, not new to coding.

Common Mistakes When Documenting with AI

  • Copying AI output without review: AI sometimes invents endpoints, hallucinates parameter names, or suggests deprecated patterns. Always review and test examples.
  • Generating docs before the API is stable: If your schema is in flux, document the stable parts first. Chasing a moving target wastes time.
  • Ignoring error cases: AI defaults to happy-path examples. Explicitly ask for error responses and edge cases.
  • One prompt for everything: Large, unfocused prompts produce shallow output. Split into endpoint-specific requests for depth.
  • Forgetting authentication details: Every example should include how auth works. Developers will not read a separate auth section first.

Quality Checklist for API Docs

Before publishing any AI-generated documentation, verify:

  • Every code example was run against the real API and returned the expected response
  • All URLs match the current environment (not dev/staging URLs)
  • Authentication instructions are current (tokens do not expire before the reader finishes reading)
  • Error codes match the actual server responses (run a few intentional bad requests)
  • SDK examples compile in the target language without modification except for API keys
  • Schema field names match the API exactly (watch for casing differences like camelCase vs snake_case)

Next Steps

With your API documented, the next logical step is to explore our System Prompts Guide to learn how to design reusable AI system prompts that maintain documentation consistency at scale.

← SQL Prompts Next: System Prompts →